参考 Python3-使用U盾完成数据的加解密(国密算法SKF接口),那么相同的功能如何使用 Flutter FFI 实现呢?
- Flutter 3.29.1
- ffi 2.1.4
- pointycastle 3.6.0
- pkcs7 1.0.5
- convert 3.1.2
代码参考如下:
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 |
import 'dart:ffi'; import 'dart:io'; import 'package:ffi/ffi.dart'; import 'package:flutter/cupertino.dart'; /// SM3 算法定义 /// /// \# define SGD_SM3 0x00000001 // ignore: constant_identifier_names const SGD_SM3 = 0x00000001; /// 异常错误 /// /// \# define SAR_UNKNOWNERR 0x0A000002 // ignore: constant_identifier_names const SAR_UNKNOWNERR = 0x0A000002; /// 对象未导出 /// /// \# define SAR_NOTEXPORTERR 0x0A00001D // ignore: constant_identifier_names const SAR_NOTEXPORTERR = 0x0A00001D; /// ECC 签名结构体 /// /// 信息安全技术 智能密码钥匙应用接口规范 GB/T 35291-2017 /// /// #define ECC_MAX_XCOORDINATE_BITS_LEN 512 /// /// typedef struct Struct_ECCSIGNATUREBLOB { /// /// BYTE r[ECC_MAX_XCOORDINATE_BITS_LEN/8]; /// /// BYTE s[ECC_MAX_XCOORDINATE_BITS_LEN/8]; /// /// } ECCSIGNATUREBLOB, *PECCSIGNATUREBLOB // ignore: constant_identifier_names const ECC_MAX_XCOORDINATE_BITS_LEN = 512; @Packed(8) // ignore: camel_case_types final class Struct_ECCSIGNATUREBLOB extends Struct { @Array(ECC_MAX_XCOORDINATE_BITS_LEN ~/ 8) external Array<Uint8> r; @Array(ECC_MAX_XCOORDINATE_BITS_LEN ~/ 8) external Array<Uint8> s; } // ignore: constant_identifier_names const TRUE = 0x00000001; // ignore: constant_identifier_names const FALSE = 0x00000000; /// ECC 公钥结构体 /// /// 信息安全技术 智能密码钥匙应用接口规范 GB/T 35291-2017 @Packed(8) // ignore: camel_case_types final class Struct_ECCPUBLICKEYBLOB extends Struct { /* * 官方文档是C语言的 ULONG,不管操作系统是32位还是64位,都要求是 4个字节。 **/ @Uint32() external int bitLen; @Array(64) external Array<Uint8> xCoordinate; @Array(64) external Array<Uint8> yCoordinate; int lengthInBytes() { return sizeOf<Struct_ECCPUBLICKEYBLOB>(); } } /// 密文数据结构,经典的Flutter变长结构体处理 /// /// 信息安全技术 智能密码钥匙应用接口规范 GB/T 35291-2017 @Packed(8) // ignore: camel_case_types final class Struct_ECCCIPHERBLOB extends Struct { /* * 官方文档是C语言的 ULONG,不管操作系统是32位还是64位,都要求是 4个字节。 **/ @Array(64) external Array<Uint8> xCoordinate; @Array(64) external Array<Uint8> yCoordinate; @Array(32) external Array<Uint8> hash; @Uint32() external int cipherLen; @Array.variable() external Array<Uint8> cipher; static Pointer<Struct_ECCCIPHERBLOB> allocate(final int length) { final lengthInBytes = lengthBytes(length); final result = calloc.allocate<Struct_ECCCIPHERBLOB>(lengthInBytes); result.ref.cipherLen = length; return result; } static int lengthBytes(final int length) { return sizeOf<Struct_ECCCIPHERBLOB>() + sizeOf<Uint8>() * length; } int lengthInBytes() { return lengthBytes(cipherLen); } } class SkfLib { /// 动态库加载 late final DynamicLibrary? _skfLib; late final int Function( int bPresent, Pointer<Uint8> szNameList, Pointer<Uint32> pulSize)? _skfEnumDev; late final int Function(Pointer<Utf8> szName, Pointer<Pointer<Void>> phDev)? _skfConnectDev; late final int Function(Pointer<Void> hDev)? _skfDisConnectDev; late final int Function(Pointer<Void> hDev, Pointer<Utf8> szAppName, Pointer<Pointer<Void>> phApplication)? _skfOpenApplication; late final int Function(Pointer<Void> hDev, Pointer<Uint8> szAppName, Pointer<Uint32> pulSize)? _skfEnumApplication; late final int Function(Pointer<Void> hApplication)? _skfCloseApplication; late final int Function( Pointer<Void> hApplication, Pointer<Uint8> szContainerName, Pointer<Uint32> pulSize)? _skfEnumContainer; late final int Function( Pointer<Void> hApplication, Pointer<Utf8> szContainerName, Pointer<Pointer<Void>> phContainer)? _skfOpenContainer; late final int Function(Pointer<Void> hContainer)? _skfCloseContainer; late final int Function( Pointer<Void> hContainer, int bSignFlag, Pointer<Struct_ECCPUBLICKEYBLOB> pbBlob, Pointer<Uint32> pulBlobLen)? _skfExportPublicKey; late final int Function(Pointer<Void> hContainer, int bSignFlag, Pointer<Uint8> pbCert, Pointer<Uint32> pulCertLen)? _skfExportCertificate; late final int Function( Pointer<Void> hDev, Pointer<Struct_ECCPUBLICKEYBLOB> pECCPubKeyBlob, Pointer<Utf8> pbPlainText, int ulPlainTextLen, Pointer<Struct_ECCCIPHERBLOB> pCipherText)? _skfExtECCEncrypt; late final int Function( Pointer<Void> hContainer, int bSignFlag, Pointer<Struct_ECCCIPHERBLOB> pCipherText, Pointer<Uint8> pbData, Pointer<Uint32> pbDataLen)? _skfECCDecrypt; late final int Function( Pointer<Void> hContainer, int ulAlgID, Pointer<Utf8> pbPlainText, int ulPlainTextLen, Pointer<Struct_ECCSIGNATUREBLOB> pSignature)? _skfECCDigestSignData; late final int Function( Pointer<Void> hContainer, int ulAlgID, Pointer<Utf8> pbPlainText, int ulPlainTextLen, Pointer<Struct_ECCSIGNATUREBLOB> pSignature)? _skfECCSignDataEx; late final int Function(Pointer<Void> hApplication, int ulPINType, Pointer<Utf8> szPIN, Pointer<Uint32> pulRetryCount)? _skfVerifyPIN; SkfLib(final String dllPath) { try { _skfLib = Platform.isMacOS || Platform.isIOS ? DynamicLibrary.process() : DynamicLibrary.open(dllPath); // 加载dll,获取句柄 } catch (e) { _skfLib = null; debugPrint('SkfLib Load Failed: $e'); } // 获取函数指针 const fnEnumDev = "SKF_EnumDev"; if (_providesSymbol(fnEnumDev)) { _skfEnumDev = _skfLib! .lookup< NativeFunction< Uint32 Function( Uint32, Pointer<Uint8>, Pointer<Uint32>)>>(fnEnumDev) .asFunction(); } else { _skfEnumDev = null; } const fnConnectDev = "SKF_ConnectDev"; if (_providesSymbol(fnConnectDev)) { _skfConnectDev = _skfLib! .lookup< NativeFunction< Uint32 Function( Pointer<Utf8>, Pointer<Pointer<Void>>)>>(fnConnectDev) .asFunction(); } else { _skfConnectDev = null; } const fnDisConnectDev = "SKF_DisConnectDev"; if (_providesSymbol(fnDisConnectDev)) { _skfDisConnectDev = _skfLib! .lookup<NativeFunction<Uint32 Function(Pointer<Void>)>>( fnDisConnectDev) .asFunction(); } else { _skfDisConnectDev = null; } const fnEnumApplication = "SKF_EnumApplication"; if (_providesSymbol(fnEnumApplication)) { _skfEnumApplication = _skfLib! .lookup< NativeFunction< Uint32 Function(Pointer<Void>, Pointer<Uint8>, Pointer<Uint32>)>>(fnEnumApplication) .asFunction(); } else { _skfEnumApplication = null; } const fnOpenApplication = "SKF_OpenApplication"; if (_providesSymbol(fnOpenApplication)) { _skfOpenApplication = _skfLib! .lookup< NativeFunction< Uint32 Function(Pointer<Void>, Pointer<Utf8>, Pointer<Pointer<Void>>)>>(fnOpenApplication) .asFunction(); } else { _skfOpenApplication = null; } const fnCloseApplication = "SKF_CloseApplication"; if (_providesSymbol(fnCloseApplication)) { _skfCloseApplication = _skfLib! .lookup<NativeFunction<Uint32 Function(Pointer<Void>)>>( fnCloseApplication) .asFunction(); } else { _skfCloseApplication = null; } const fnEnumContainer = "SKF_EnumContainer"; if (_providesSymbol(fnEnumContainer)) { _skfEnumContainer = _skfLib! .lookup< NativeFunction< Uint32 Function(Pointer<Void>, Pointer<Uint8>, Pointer<Uint32>)>>(fnEnumContainer) .asFunction(); } else { _skfEnumContainer = null; } const fnOpenContainer = "SKF_OpenContainer"; if (_providesSymbol(fnOpenContainer)) { _skfOpenContainer = _skfLib! .lookup< NativeFunction< Uint32 Function(Pointer<Void>, Pointer<Utf8>, Pointer<Pointer<Void>>)>>(fnOpenContainer) .asFunction(); } else { _skfOpenContainer = null; } const fnCloseContainer = "SKF_CloseContainer"; if (_providesSymbol(fnCloseContainer)) { _skfCloseContainer = _skfLib! .lookup<NativeFunction<Uint32 Function(Pointer<Void>)>>( fnCloseContainer) .asFunction(); } else { _skfCloseContainer = null; } const fnExportPublicKey = "SKF_ExportPublicKey"; if (_providesSymbol(fnExportPublicKey)) { _skfExportPublicKey = _skfLib! .lookup< NativeFunction< Uint32 Function( Pointer<Void>, Uint32, Pointer<Struct_ECCPUBLICKEYBLOB>, Pointer<Uint32>)>>(fnExportPublicKey) .asFunction(); } else { _skfExportPublicKey = null; } const fnExportCertificate = "SKF_ExportCertificate"; if (_providesSymbol(fnExportCertificate)) { _skfExportCertificate = _skfLib! .lookup< NativeFunction< Uint32 Function(Pointer<Void>, Uint32, Pointer<Uint8>, Pointer<Uint32>)>>(fnExportCertificate) .asFunction(); } else { _skfExportCertificate = null; } const fnExtECCEncrypt = "SKF_ExtECCEncrypt"; if (_providesSymbol(fnExtECCEncrypt)) { _skfExtECCEncrypt = _skfLib! .lookup< NativeFunction< Uint32 Function( Pointer<Void>, Pointer<Struct_ECCPUBLICKEYBLOB>, Pointer<Utf8>, Uint32, Pointer<Struct_ECCCIPHERBLOB>)>>(fnExtECCEncrypt) .asFunction(); } else { _skfExtECCEncrypt = null; } const fnECCDecrypt = "SKF_ECCDecrypt"; if (_providesSymbol(fnECCDecrypt)) { _skfECCDecrypt = _skfLib! .lookup< NativeFunction< Uint32 Function( Pointer<Void>, Uint32, Pointer<Struct_ECCCIPHERBLOB>, Pointer<Uint8>, Pointer<Uint32>)>>(fnECCDecrypt) .asFunction(); } else { _skfECCDecrypt = null; } const fnECCDigestSignData = "SKF_ECCDigestSignData"; if (_providesSymbol(fnECCDigestSignData)) { _skfECCDigestSignData = _skfLib! .lookup< NativeFunction< Uint32 Function(Pointer<Void>, Uint32, Pointer<Utf8>, Uint32, Pointer<Struct_ECCSIGNATUREBLOB>)>>(fnECCDigestSignData) .asFunction(); } else { _skfECCDigestSignData = null; } const fnECCSignDataEx = "SKF_ECCSignDataEx"; if (_providesSymbol(fnECCSignDataEx)) { _skfECCSignDataEx = _skfLib! .lookup< NativeFunction< Uint32 Function(Pointer<Void>, Uint32, Pointer<Utf8>, Uint32, Pointer<Struct_ECCSIGNATUREBLOB>)>>(fnECCSignDataEx) .asFunction(); } else { _skfECCSignDataEx = null; } const fnVerifyPIN = "SKF_VerifyPIN"; if (_providesSymbol(fnVerifyPIN)) { _skfVerifyPIN = _skfLib! .lookup< NativeFunction< Uint32 Function(Pointer<Void>, Uint32, Pointer<Utf8>, Pointer<Uint32>)>>(fnVerifyPIN) .asFunction(); } else { _skfVerifyPIN = null; } } /// Checks whether this dynamic library provides a symbol with the given name. bool _providesSymbol(final String symbolName) { return _skfLib?.providesSymbol(symbolName) ?? false; } @mustCallSuper void close() { _skfLib?.close(); } /// 功能描述: /// /// 获得当前系统中的设备列表。 /// /// 参数: /// /// [bPresent] [IN] 为 TRUE 表示获取当前设备状态为存在的设备列表。 /// 为 FALSE 表示取当前取得支持的设备列表。 /// /// [szNameList] [OUT] 设备名称列表。如果该参数为 NULL ,将由 pulSize 返回所需要的内存空间大小。 /// 每个设备的名称以单个 '\0' 结束,以双 '\0' 表示列表结束。 /// /// [pulSize] [IN, OUT] 输入时表示设备名称列表的缓冲区长度,输出时表示 szNameList 所占用的空间大小。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_EnumDev(final int bPresent, final Pointer<Uint8> szNameList, final Pointer<Uint32> pulSize) { if (null != _skfEnumDev) { return _skfEnumDev(bPresent, szNameList, pulSize); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 通过设备名称连接设备,返回设备的句柄。 /// /// 参数: /// /// [szName] [IN] 设备名称。 /// /// [phDev] [OUT] 返回设备操作句柄。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_ConnectDev( final Pointer<Utf8> szName, final Pointer<Pointer<Void>> phDev) { if (null != _skfConnectDev) { return _skfConnectDev(szName, phDev); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 断开一个已经连接的设备,并释放句柄。 /// /// 参数: /// /// [hDev] [IN] 连接设备时返回的设备句柄。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_DisConnectDev(final Pointer<Void> hDev) { if (null != _skfDisConnectDev) { return _skfDisConnectDev(hDev); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 枚举设备中存在的所有应用。 /// /// 参数: /// /// [hDev] [IN] 连接设备时返回的设备句柄。 /// /// [szAppName] [OUT] 返回应用名称列表,如果该参数为空,将由 pulSize 返回所需要的内存空间大小。 /// 每个应用的名称以单个 '\0' 结束,以双 '\0' 表示列表结束。 /// /// [pulSize] [IN, OUT] 输入时表示应用名称列表的缓冲区长度,输出时表示 szAppName 所占用的空间大小。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_EnumApplication(final Pointer<Void> hDev, final Pointer<Uint8> szAppName, final Pointer<Uint32> pulSize) { if (null != _skfEnumApplication) { return _skfEnumApplication(hDev, szAppName, pulSize); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 打开指定的应用。 /// /// 参数: /// /// [hDev] [IN] 连接设备时返回的设备句柄。 /// /// [szAppName] [IN] 应用名称。 /// /// [phApplication] [OUT] 应用的句柄。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_OpenApplication( final Pointer<Void> hDev, final Pointer<Utf8> szAppName, final Pointer<Pointer<Void>> phApplication) { if (null != _skfOpenApplication) { return _skfOpenApplication(hDev, szAppName, phApplication); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 关闭应用并释放应用句柄。 /// /// 参数: /// /// [hApplication] [IN] 应用句柄。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_CloseApplication(final Pointer<Void> hApplication) { if (null != _skfCloseApplication) { return _skfCloseApplication(hApplication); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 枚举容器下所有容器并返回容器名称列表。 /// /// 参数: /// /// [hApplication] [IN] 应用句柄。 /// /// [szContainerName] [OUT] 指向容器名称列表缓冲区,如果该参数为 NULL 时,pulSize 表示返回数据所需缓冲区的长度, /// 如果此参数不为 NULL 时,返回容器名称列表,每个容器名以 '\0' 结束,列表以双 '\0' 结束。 /// /// [pulSize] [IN, OUT] 输入时表示 szContainerName 缓冲区长度,输出时表示容器名称列表的长度。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_EnumContainer(final Pointer<Void> hApplication, final Pointer<Uint8> szContainerName, final Pointer<Uint32> pulSize) { if (null != _skfEnumContainer) { return _skfEnumContainer(hApplication, szContainerName, pulSize); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 获取容器句柄。 /// /// 参数: /// /// [hApplication] [IN] 应用句柄。 /// /// [szContainerName] [IN] 容器的名称。 /// /// [phContainer] [OUT] 返回所打开容器的句柄。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_OpenContainer( final Pointer<Void> hApplication, final Pointer<Utf8> szContainerName, final Pointer<Pointer<Void>> phContainer) { if (null != _skfOpenContainer) { return _skfOpenContainer(hApplication, szContainerName, phContainer); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 关闭容器句柄,并释放容器句柄相关资源。 /// /// 参数: /// /// [hContainer] [IN] 容器句柄。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_CloseContainer(final Pointer<Void> hContainer) { if (null != _skfCloseContainer) { return _skfCloseContainer(hContainer); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 从导出公钥。 /// /// 参数: /// /// [hContainer] [IN] 容器句柄。 /// /// [bSignFlag] [IN] TRUE 表示签名证书,FALSE 表示加密证书。 /// /// [pbBlob] [OUT] 指向公钥内容缓冲区,如果此参数为 NULL 时,pulBlobLen 返回数据所需要 /// 缓冲区长度,如果此参数不为 NULL 时,返回公钥内容。 /// /// [pulBlobLen] [IN/OUT] 输入时表示 pbBlob 缓冲区的长度,输出时表示证书内容的长度。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_ExportPublicKey( final Pointer<Void> hContainer, final int bSignFlag, final Pointer<Struct_ECCPUBLICKEYBLOB> pbBlob, final Pointer<Uint32> pulBlobLen) { if (null != _skfExportPublicKey) { return _skfExportPublicKey(hContainer, bSignFlag, pbBlob, pulBlobLen); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 从容器内导出数字证书。 /// /// 参数: /// /// [hContainer] [IN] 容器句柄。 /// /// [bSignFlag] [IN] TRUE 表示签名证书,FALSE 表示加密证书。 /// /// [pbCert] [OUT] 指向证书内容缓冲区,如果此参数为 NULL 时,pulCertLen 返回数据所需要 /// 缓冲区长度,如果此参数不为 NULL 时,返回数字证书内容。 /// /// [pulCertLen] [IN/OUT] 输入时表示 pbCert 缓冲区的长度,输出时表示证书内容的长度。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_ExportCertificate(final Pointer<Void> hContainer, final int bSignFlag, final Pointer<Uint8> pbCert, final Pointer<Uint32> pulCertLen) { if (null != _skfExportCertificate) { return _skfExportCertificate(hContainer, bSignFlag, pbCert, pulCertLen); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 使用外部传入的 ECC 公钥对输入数据做加密运算并输出结果。 /// /// 参数: /// /// [hDev] [IN] 设备句柄。 /// /// [pECCPubKeyBlob] [IN] ECC公钥数据结构。 /// /// [pbPlainText] [IN] 待加密的明文数据。 /// /// [ulPlainTextLen] [IN] 待加密的明文数据长度。 /// /// [pCipherText] [OUT] 密文数据。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_ExtECCEncrypt( final Pointer<Void> hDev, final Pointer<Struct_ECCPUBLICKEYBLOB> pECCPubKeyBlob, final Pointer<Utf8> pbPlainText, final int ulPlainTextLen, final Pointer<Struct_ECCCIPHERBLOB> pCipherText) { if (null != _skfExtECCEncrypt) { return _skfExtECCEncrypt( hDev, pECCPubKeyBlob, pbPlainText, ulPlainTextLen, pCipherText); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 私钥解密。 /// /// 参数: /// /// [hContainer] [IN] 密钥容器句柄。 /// /// [bSignFlag] [IN] TRUE 表示签名证书,FALSE 表示加密证书。 /// /// [pCipherText] [IN] 加密数据的结构。 /// /// [pbData] [OUT] 解密后的明文数据。 /// /// [pbDataLen] [OUT] 明文数据长度。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_ECCDecrypt( final Pointer<Void> hContainer, final int bSignFlag, final Pointer<Struct_ECCCIPHERBLOB> pCipherText, final Pointer<Uint8> pbData, final Pointer<Uint32> pbDataLen) { if (null != _skfECCDecrypt) { return _skfECCDecrypt( hContainer, bSignFlag, pCipherText, pbData, pbDataLen); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 厂商实现的 ECC 数据签名扩展。 /// /// 参数: /// /// [hContainer] [IN] 密钥容器句柄。 /// /// [ulAlgID] [IN] 杂凑算法标识,这里选择SGD_SM3(0x00000001),表明使用SM3算法。 /// /// [pbPlainText] [IN] 待签名的明文数据。 /// /// [ulPlainTextLen] [IN] 待签名的明文数据长度。 /// /// [pSignature] [OUT] 签名结果。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_ECCSignDataEx( final Pointer<Void> hContainer, final int ulAlgID, final Pointer<Utf8> pbPlainText, final int ulPlainTextLen, final Pointer<Struct_ECCSIGNATUREBLOB> pSignature) { // WQ 扩展接口 SKF_ECCSignDataEx // FT/HB 扩展接口 SKF_ECCDigestSignData if (null != _skfECCDigestSignData) { return _skfECCDigestSignData( hContainer, ulAlgID, pbPlainText, ulPlainTextLen, pSignature); } else if (null != _skfECCSignDataEx) { return _skfECCSignDataEx( hContainer, ulAlgID, pbPlainText, ulPlainTextLen, pSignature); } return SAR_NOTEXPORTERR; } /// 功能描述: /// /// 校验 PIN 码。校验成功后,会获得相应的权限,如果 PIN 码错误,会返回 PIN 码的重试次数, /// 当重试次数为 0 时表示 PIN 码已经锁死。 /// /// 参数: /// /// [hApplication] [IN] 应用句柄。 /// /// [ulPINType] [IN] PIN 类型。 0 是管理员账户,1 为普通用户,这个参数一般选择 1。 /// /// [szPIN] [IN] PIN 值。 /// /// [pulRetryCount] [OUT] 出错后返回的重试次数。 /// /// 返回值: /// /// SAR_OK : 成功。 /// /// 其他: 错误码。 // ignore: non_constant_identifier_names int SKF_VerifyPIN(final Pointer<Void> hApplication, final int ulPINType, final Pointer<Utf8> szPIN, final Pointer<Uint32> pulRetryCount) { if (null != _skfVerifyPIN) { return _skfVerifyPIN(hApplication, ulPINType, szPIN, pulRetryCount); } return SAR_NOTEXPORTERR; } } |
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
import 'dart:convert'; import 'dart:ffi'; import 'dart:typed_data'; import 'package:convert/convert.dart'; import 'package:ffi/ffi.dart'; import 'package:pkcs7/pkcs7.dart'; import 'package:pointycastle/asn1.dart'; import 'skf_lib.dart'; class SkfProvider extends SkfLib { /// 设备名 late final String _devName; /// 设备句柄 late Pointer<Void> _devHandle; /// 应用名 late final String _appName; /// 应用句柄 late Pointer<Void> _appHandle; /// 容器名 late final List<String> _cntNames; /// 容器句柄 late Pointer<Void> _cntHandle; int error = 0; SkfProvider(super.dllPath) { _initHandle(); } /// 句柄获取 /// /// 获取设备、应用、容器句柄 _initHandle() { _devName = _getDevName(); // 获取设备名 _devHandle = _connectDev(); // 获取设备句柄 需要用到设备名 _appName = _getAppName(); // 获取应用名 _appHandle = _openApplication(); // 定义应用句柄 _cntNames = _getCntNames(); // 获取容器名 if (0 == error) { /// 获取容器名的时候返回的error为0,正常执行 /// 此处选择第一个容器作为ECC密钥对,如果第一个不是ECC密钥对,可能导致应用闪退 /// 请根据实际情况进行相关调整 _cntHandle = _openContainer(_cntNames[1]); } } /// 句柄释放 /// /// 释放设备、应用、容器句柄 @override close() { if (nullptr != _cntHandle) { SKF_CloseContainer(_cntHandle); _cntHandle = nullptr; } if (nullptr != _appHandle) { SKF_CloseApplication(_appHandle); _appHandle = nullptr; } if (nullptr != _devHandle) { SKF_DisConnectDev(_devHandle); _devHandle = nullptr; } super.close(); } /// 获取设备名 /// /// 多设备的情况只会获取到第一个设备 String _getDevName() { final pulSize = calloc<Uint32>(); // 为指针分配内存 error = SKF_EnumDev(TRUE, nullptr, pulSize); final szNameList = calloc.allocate<Uint8>(pulSize.value); //为szNameList分配内存 error = SKF_EnumDev(TRUE, szNameList, pulSize); calloc.free(pulSize); final String devName = szNameList.cast<Utf8>().toDartString(); calloc.free(szNameList); return devName; } Pointer<Void> _connectDev() { final phDev = calloc<Pointer<Void>>(); error = SKF_ConnectDev(_devName.toNativeUtf8(), phDev); // 连接设备 final res = phDev.value; calloc.free(phDev); return res; } String _getAppName() { final pulSize = calloc<Uint32>(); // 用于获取应用名长度 error = SKF_EnumApplication(_devHandle, nullptr, pulSize); final szNameList = calloc<Uint8>(pulSize.value); //为szNameList分配内存 error = SKF_EnumApplication( _devHandle, szNameList, pulSize); // 获取应用名,这里默认返回第一个应用名 calloc.free(pulSize); final String appName = szNameList.cast<Utf8>().toDartString(); calloc.free(szNameList); return appName; } Pointer<Void> _openApplication() { final phApp = calloc<Pointer<Void>>(); error = SKF_OpenApplication(_devHandle, _appName.toNativeUtf8(), phApp); // 打开应用 final res = phApp.value; calloc.free(phApp); return res; } List<String> _getCntNames() { final List<String> cntNames = []; using((Arena arena) { final pulSize = arena<Uint32>(); // 用于获取应用名长度: error = SKF_EnumContainer(_appHandle, nullptr, pulSize); final szNameList = arena<Uint8>(pulSize.value); //为szNameList分配内存 // 由于szNameList是以'\0'为分隔符,获取多个容器名列表切分获取 error = SKF_EnumContainer(_appHandle, szNameList, pulSize); int start = 0; final Utf8Decoder decoder = const Utf8Decoder(allowMalformed: true); final szNameListArr = szNameList.asTypedList(pulSize.value); for (int i = 0; i < pulSize.value; i++) { if (0 == szNameList[i]) { if (0 != szNameList[start]) { final name = decoder.convert(szNameListArr, start, i); cntNames.add(name); start = i + (i <= pulSize.value - 1 ? 1 : 0); // 此处提防最后一个字符越界 } } } }); return cntNames; // 容器列表 } Pointer<Void> _openContainer(final String cntName) { final phCnt = calloc<Pointer<Void>>(); // 容器句柄 error = SKF_OpenContainer(_appHandle, cntName.toNativeUtf8(), phCnt); // 打开容器 final res = phCnt.value; calloc.free(phCnt); return res; } /// 1-导出ECC的加密密钥对的公钥 /// /// 2-用公钥加密SKF_ExtECCEncrypt Pointer<Struct_ECCCIPHERBLOB> eccEncrypt(final String plainText) { // 创建公钥接收对象 final pbBlob = calloc<Struct_ECCPUBLICKEYBLOB>(); final pulBlobLen = calloc<Uint32>(); pulBlobLen.value = pbBlob.ref.lengthInBytes(); error = SKF_ExportPublicKey(_cntHandle, FALSE, pbBlob, pulBlobLen); calloc.free(pulBlobLen); final pCipherText = Struct_ECCCIPHERBLOB.allocate(plainText.length); final nativeText = plainText.toNativeUtf8(); // 用公钥进行加密 error = SKF_ExtECCEncrypt( _devHandle, pbBlob, nativeText, nativeText.length, pCipherText); calloc.free(pbBlob); return pCipherText; } /// 1-导出ECC的加密密钥对的公钥 /// /// 2-用公钥加密SKF_ExtECCEncrypt /// /// 3-转成Hex字符串 String eccEncryptHex(final String plainText) { final cipherText = eccEncrypt(plainText); // 将密文结构内容转成Hex字符串 final res = cipherTextToStrHex(cipherText); calloc.free(cipherText); return res; } String eccDecrypt(final Pointer<Struct_ECCCIPHERBLOB> cipherText) { var plainText = ""; using((Arena arena) { final plainTextLen = arena<Uint32>(); // 解密,传None,获得plain_text的长度 error = SKF_ECCDecrypt(_cntHandle, FALSE, cipherText, nullptr, plainTextLen); // plain_text分配空间 final plainTextBuffer = arena<Uint8>(plainTextLen.value); // 解密 error = SKF_ECCDecrypt( _cntHandle, FALSE, cipherText, plainTextBuffer, plainTextLen); // 返回明文 plainText = plainTextBuffer.cast<Utf8>().toDartString(); }); return plainText; } String eccDecryptHex(final String cipherHex) { final cipherText = strHexToCipherText(cipherHex); // 先将Hex密文字符串转为ECC密文结构 final res = eccDecrypt(cipherText); // 解密 calloc.free(cipherText); return res; } Pointer<Struct_ECCSIGNATUREBLOB> eccSignEx(final String plainText) { // 签名返回结果 final pbBlob = calloc<Struct_ECCSIGNATUREBLOB>(); // WQ 扩展接口 SKF_ECCSignDataEx // FT/HB 扩展接口 SKF_ECCDigestSignData final nativeText = plainText.toNativeUtf8(); error = SKF_ECCSignDataEx( _cntHandle, SGD_SM3, nativeText, nativeText.length, pbBlob); return pbBlob; } /// 1-对原文进行SM2签名 /// /// 2-获取签名证书信息 /// /// 3-返回签名证书字符数组,SM2签名结果 (ByteData, ByteData, ByteData) (ByteData, ByteData, ByteData) sm2Sign(final String plainText) { //签名 final signRes = eccSignEx(plainText); // 取ECC签名的后 32 位 作为SM2签名,参考 // https: // github.com/guanzhi/GmSSL/blob/master/src/skf/skf.c // SKF_ECCSIGNATUREBLOB_to_SM2_SIGNATURE const int validBytes = 32; final sm2R = ByteData(validBytes); for (int i = validBytes; i < 64; i++) { sm2R.setUint8(i - validBytes, signRes.ref.r[i]); } final sm2S = ByteData(validBytes); for (int i = validBytes; i < 64; i++) { sm2S.setUint8(i - validBytes, signRes.ref.s[i]); } calloc.free(signRes); var certDerBytes = ByteData(0); using((Arena arena) { // 导出签名证书 final pulBlobLen = arena<Uint32>(); error = SKF_ExportCertificate(_cntHandle, TRUE, nullptr, pulBlobLen); // 申请内存 final certDer = arena<Uint8>(pulBlobLen.value); error = SKF_ExportCertificate(_cntHandle, TRUE, certDer, pulBlobLen); certDerBytes = ByteData(pulBlobLen.value); for (int i = 0; i < pulBlobLen.value; i++) { certDerBytes.setUint8(i, (certDer + i).value); } }); return (certDerBytes, sm2R, sm2S); } /// 1-对原文进行签名 /// /// 2-获取签名证书信息 /// /// 3-对报文进行P7 DER格式封装 Uint8List sm2SignP7DER(final String plainText) { final (certDer, sm2R, sm2S) = sm2Sign(plainText); return buildSm2SignP7DER(plainText, certDer, sm2R, sm2S); } /// 对报文进行签名,并对结果进行 P7 格式封装,返回结果使用HEX格式 String sm2SignP7DERHex(final String plainText) { final res = sm2SignP7DER(plainText); return hex.encoder.convert(res); } /// 构建 P7 DER 格式的SM2签名报文 /// /// 1-plainText 签名原文 /// /// 2-certDer DER格式的签名证书 /// /// 3-sm2R SM2格式签名返回的 r 32位字符数组 /// /// 4-sm2S SM2格式签名返回的 s 32位字符数组 Uint8List buildSm2SignP7DER(final String plainText, final ByteData certDer, final ByteData sm2R, final ByteData sm2S) { // ignore: constant_identifier_names const CONTEXT_SPECIFIC = ASN1Tags.TAGGED | ASN1Tags.CONSTRUCTED | 0; //A0 // SM3 签名算法 OID final sm3DigestOid = ASN1ObjectIdentifier.fromIdentifierString("1.2.156.10197.1.401"); // SM3 签名算法 // 'digest_algorithms' final sm3DigestAlg = ASN1Sequence(elements: [ sm3DigestOid, ASN1Null(), ]); // 签名算法类型 SM3withSM2 // SM2 签名算法 OID final sm2SignOid = ASN1ObjectIdentifier.fromIdentifierString("1.2.156.10197.1.301.1"); // SM2 签名算法 final sm2SignAlg = ASN1Sequence(elements: [ sm2SignOid, ASN1Null(), ]); final X509 cert = X509.fromDer(certDer.buffer.asUint8List()); final certSet = ASN1Sequence(elements: [ // 'certificate': cert # 证书 cert.asn1, // cert.signatureAlgorithmOI, // ASN1BitString.fromBytes(cert.signatureValue) ]); final signVal = BytesBuilder(); signVal.add(sm2R.buffer.asUint8List()); signVal.add(sm2S.buffer.asUint8List()); final signerInfo = ASN1Sequence(elements: [ // 'version' ASN1Integer.fromtInt(1), // 'sid' 签名证书信息 'issuer_and_serial_number' ASN1Sequence(elements: [ // 'issuer' cert.asn1Issuer, // 'serial_number' ASN1Integer(cert.serialNumber) ]), // 'digest_algorithm' sm3DigestAlg, // 摘要算法 // 'signature_algorithm' sm2SignAlg, // 签名算法 // 'signature' ASN1OctetString(octets: signVal.toBytes()) // 签名信息 (OCTET STRING) ]); // 构建完整证书的 ASN.1 PKCS#7 SignedData 结构 final signedData = ASN1Sequence(elements: [ // 'version' 签名版本 v1 ASN1Integer.fromtInt(1), // 'digest_algorithms' 签名算法 ASN1Set(elements: [ ASN1Sequence(elements: [ // SM3withSM2 sm3DigestOid, // 'algorithm' ASN1Null() // 'parameters' ]) ]), // 'encap_content_info' 签名载核(业务)数据 ASN1Sequence(elements: [ // 载核(业务)数据类型 (PKCS #7) ASN1ObjectIdentifier.fromIdentifierString( '1.2.840.113549.1.7.1'), //'content_type' // 签名载核(业务)数据 ASN1Set(elements: [ ASN1OctetString(octets: utf8.encoder.convert(plainText)) ], tag: CONTEXT_SPECIFIC) // 'content' ]), // 'certificates' 证书集合 ASN1Set(elements: [certSet], tag: CONTEXT_SPECIFIC), // 'signer_infos' 签名信息 ASN1Set(elements: [signerInfo]) ]); // 数据传输封装 final payloadContent = ASN1Sequence(elements: [ // 数据类型 (PKCS #7) ASN1ObjectIdentifier.fromIdentifierString( '1.2.840.113549.1.7.2'), //'content_type' // 签名数据 ASN1Set(elements: [signedData]) // 'content' ]); return payloadContent.encode(); } /// PIN校验 /// /// user_pin:字符串 /// /// return:返回剩余尝试次数 int verifyPIN(final String userPin) { var leftTimes = 0; final int ulPINType = 1; // PIN类型,1表示用户PIN using((Arena arena) { final pulRetryCount = arena<Uint32>(); // PIN剩余尝试次数 // 调用验证PIN接口 error = SKF_VerifyPIN( _appHandle, ulPINType, userPin.toNativeUtf8(), pulRetryCount); leftTimes = pulRetryCount.value; }); return leftTimes; } /// 将Hex字符串转成ECC密文结构 /// /// strHex:Hex字符串 /// /// return:ECC密文结构 Pointer<Struct_ECCCIPHERBLOB> strHexToCipherText(final String strHex) { // 密文结构中 Cipher 长度(C3) final cipherLen = (strHex.length - Struct_ECCCIPHERBLOB.lengthBytes(0) * 2) ~/ 2; final pCipherText = Struct_ECCCIPHERBLOB.allocate(cipherLen); // 声明pCipherText密文结构变量 final xCoordinateHex = strHex.substring(0, 64); // 获取密文结构的 XCoordinate 的Hex字符串 final yCoordinateHex = strHex.substring(64, 128); // 获取密文结构的 YCoordinate 的Hex字符串 final hashHex = strHex.substring(128, 192); // 获取密文结构的 HASH 的Hex字符串 final cipherTextHex = strHex.substring(192); // C2:密文结构中的Cipher // 为密文结构中的每部分赋值 for (int i = 0; i < 32; i++) { pCipherText.ref.xCoordinate[32 + i] = int.parse(xCoordinateHex.substring(i * 2, 2), radix: 16); } for (int i = 0; i < 32; i++) { pCipherText.ref.yCoordinate[32 + i] = int.parse(yCoordinateHex.substring(i * 2, 2), radix: 16); } for (int i = 0; i < 32; i++) { pCipherText.ref.hash[i] = int.parse(hashHex.substring(i * 2, 2), radix: 16); } // 密文部分转为Uint8类型 for (int i = 0; i < cipherLen; i++) { pCipherText.ref.cipher[i] = int.parse(cipherTextHex.substring(i * 2, 2), radix: 16); } return pCipherText; } /// 将ECC密文结构转成Hex字符串 String cipherTextToStrHex(final Pointer<Struct_ECCCIPHERBLOB> cipherText) { final textHex = StringBuffer(); // 将密文结构内容转成Hex字符串 for (int i = 32; i < 64; i++) { // 获取密文结构中 XCoordinate textHex.write( cipherText.ref.xCoordinate[i].toRadixString(16).padLeft(2, '0')); } for (int i = 32; i < 64; i++) { // 获取密文结构中 YCoordinate textHex.write( cipherText.ref.yCoordinate[i].toRadixString(16).padLeft(2, '0')); } for (int i = 0; i < 32; i++) { // 获取密文结构中 HASH textHex.write(cipherText.ref.hash[i].toRadixString(16).padLeft(2, '0')); } for (int i = 0; i < cipherText.ref.cipherLen; i++) { // 将 Cipher 转成Hex字符串 textHex.write(cipherText.ref.cipher[i].toRadixString(16).padLeft(2, '0')); } return textHex.toString().toUpperCase(); } } |
使用方式:
1 2 3 4 5 6 7 |
const path = "/opt/apps/xxxx.so"; skfProvider = SkfProvider(path); skfProvider?.verifyPIN("123456"); skfProvider?.eccEncryptHex("123456"); const plain = "123456"; var res = skfProvider?.sm2SignP7DERHex(plain); debugPrint(res); |
参考链接
- Python3-使用U盾完成数据的加解密(国密算法SKF接口)
- Convert a List<int> into a Pointer<Uint32> #127
- 如何使用Dart FFI看这篇文章就够了
- 如何在 Flutter 中调用 C++ 代码
- Array<T extends NativeType>.variable constructor
- Flutter Dart FFI Pointer<Uint8>类型如何转成数组或String
- Dart FFI 数据类型映射
- How to pass huge objects across isolates and/or ffi, without huge memory and cpu footprint? #1862
- Packaging and Distributing Flutter Desktop Apps : The Missing Guide for Open Source & Indie Developers — Creating Linux Debian (.deb) & RPM (.rpm) builds [Part 3 of 3]
- flutter_to_debian 2.0.2