diff --git a/flutter_rsa_ohos/.gitignore b/flutter_rsa_ohos/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..05bcbfb73402c99b9f31b5ca75dd8c182f9e9d47 --- /dev/null +++ b/flutter_rsa_ohos/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.packages +build/ +test/ diff --git a/flutter_rsa_ohos/.metadata b/flutter_rsa_ohos/.metadata new file mode 100644 index 0000000000000000000000000000000000000000..bc69efa395049609219862a3cf7effdf67d6acab --- /dev/null +++ b/flutter_rsa_ohos/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled. + +version: + revision: 09241c11536f582a5b1f161afb591896dee3e36e + channel: dev + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 09241c11536f582a5b1f161afb591896dee3e36e + base_revision: 09241c11536f582a5b1f161afb591896dee3e36e + - platform: ohos + create_revision: 09241c11536f582a5b1f161afb591896dee3e36e + base_revision: 09241c11536f582a5b1f161afb591896dee3e36e + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/flutter_rsa_ohos/CHANGELOG.md b/flutter_rsa_ohos/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..fd91ecfdf17a21968366cf4c79a85b56b010e121 --- /dev/null +++ b/flutter_rsa_ohos/CHANGELOG.md @@ -0,0 +1,3 @@ +## 1.0.0 + +* Support OpenHarmony diff --git a/flutter_rsa_ohos/LICENSE b/flutter_rsa_ohos/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ac79fab6471dda08df74a074449bd02bccf5162a --- /dev/null +++ b/flutter_rsa_ohos/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Gerson Alexander Pardo Gamez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/flutter_rsa_ohos/README.md b/flutter_rsa_ohos/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e906ff2bb434a441f84c1639a13499b4e71a84fa --- /dev/null +++ b/flutter_rsa_ohos/README.md @@ -0,0 +1,137 @@ +# flutter_rsa_ohos + +Library for use RSA with support for ohos + +## Usage +In _pubspec.yaml_: + +```yaml +dependencies: + fast_rsa: ^3.6.3 + flutter_rsa_ohos: ^1.0.0 +``` + +### Encrypt methods + +```dart +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +var result = await RSA.encryptOAEP(message, label, Hash.HASH_SHA256, publicKey) +var result = await RSA.encryptPKCS1v15(message, publicKey) + +var result = await RSA.encryptOAEPBytes(messageBytes, label, Hash.SHA256, publicKey) +var result = await RSA.encryptPKCS1v15Bytes(messageBytes, publicKey) + +``` + +### Decrypt methods + +```dart +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +var result = await RSA.decryptOAEP(message, label, Hash.HASH_SHA256, privateKey) +var result = await RSA.decryptPKCS1v15(message, privateKey) + +var result = await RSA.decryptOAEPBytes(messageBytes, label, Hash.SHA256, privateKey) +var result = await RSA.decryptPKCS1v15Bytes(messageBytes, privateKey) + +``` + +### Sign methods + +```dart +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +var result = await RSA.signPSS(message, Hash.SHA256, SaltLength.SALTLENGTH_AUTO, privateKey) +var result = await RSA.signPKCS1v15(message, Hash.SHA256, privateKey) + +var result = await RSA.signPSSBytes(messageBytes, Hash.SHA256, SaltLength.SALTLENGTH_AUTO, privateKey) +var result = await RSA.signPKCS1v15Bytes(messageBytes, Hash.SHA256, privateKey) + +``` + +### Verify methods + +```dart +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +var result = await RSA.verifyPSS(signature, message, Hash.SHA256, SaltLength.SALTLENGTH_AUTO, publicKey) +var result = await RSA.verifyPKCS1v15(signature, message, Hash.SHA256, publicKey) + +var result = await RSA.verifyPSSBytes(signatureBytes, messageBytes, Hash.SHA256, SaltLength.SALTLENGTH_AUTO, publicKey) +var result = await RSA.verifyPKCS1v15Bytes(signatureBytes, messageBytes, Hash.SHA256, publicKey) + +``` + +### Generate Methods + +```dart +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +var result = await RSA.generate(2048) + +``` + +### Convert Methods + +```dart +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +var result = await RSA.convertPrivateKeyToPKCS8(privateKey) +var result = await RSA.convertPrivateKeyToPKCS1(privateKey) + +var result = await RSA.convertPublicKeyToPKIX(publicKey) +var result = await RSA.convertPublicKeyToPKCS1(publicKey) + +var result = await RSA.encryptPrivateKey(privateKey, password, PEMCipher.PEMCIPHER_AES256) +var result = await RSA.decryptPrivateKey(privateKeyEncrypted, password) +``` + +### Util Methods + +```dart +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +var result = await RSA.hash(message, Hash.SHA256) +var result = await RSA.base64(message) + +``` + +## Not Supported Interface + +The following interfaces are not supported currently. + +| Interface | Function | Android | Ohos | +| ---------------------------- | ---------------------------------------- | ------------------ | ------------------ | +| decryptOAEPBytes | 填充模式PKCS1_OAEP的解密方法,返回字节 | :white_check_mark: | :white_check_mark: | +| decryptPKCS1v15Bytes | 填充模式PKCS1的解密方法,返回字节 | :white_check_mark: | :white_check_mark: | +| encryptOAEPBytes | 填充模式PKCS1_OAEP的加密方法,返回字节 | :white_check_mark: | :white_check_mark: | +| encryptPKCS1v15Bytes | 填充模式PKCS1的加密方法,返回字节 | :white_check_mark: | :white_check_mark: | +| signPSSBytes | 使用PSS签名,返回字节 | :white_check_mark: | :white_check_mark: | +| signPKCS1v15Bytes | 使用PKCS1v15签名,返回字节 | :white_check_mark: | :white_check_mark: | +| convertPrivateKeyToPKCS8 | 私钥转换PKCS8格式字符串 | :white_check_mark: | :white_check_mark: | +| convertPrivateKeyToPKCS1 | 私钥转换PKCS1格式字符串 | :white_check_mark: | :white_check_mark: | +| convertPublicKeyToPKIX | 公钥转换为X.509格式的字符串 | :white_check_mark: | :white_check_mark: | +| convertPublicKeyToPKCS1 | 公钥转换为PKCS1格式的字符串 | :white_check_mark: | :white_check_mark: | +| decryptPrivateKey | 对PEM格式字符串的私钥进行解密 | :white_check_mark: | :white_check_mark: | +| encryptPrivateKey | 对私钥进行加密后转为PEM格式字符串 | :white_check_mark: | :white_check_mark: | +| decryptOAEP | 填充模式PKCS1_OAEP的解密方法,返回字符串 | :white_check_mark: | :white_check_mark: | +| decryptPKCS1v15 | 填充模式PKCS1的解密方法,返回字符串 | :white_check_mark: | :white_check_mark: | +| encryptOAEP | 填充模式PKCS1_OAEP的加密方法,返回字符串 | :white_check_mark: | :white_check_mark: | +| encryptPKCS1v15 | 填充模式PKCS1的加密方法,返回字符串 | :white_check_mark: | :white_check_mark: | +| signPSS | 使用PSS签名,返回字符串 | :white_check_mark: | :white_check_mark: | +| signPKCS1v15 | 使用PKCS1v15签名,返回字符串 | :white_check_mark: | :white_check_mark: | +| hash | 计算给定消息的哈希值,返回16进制字符串 | :white_check_mark: | :white_check_mark: | +| base64 | 将字符串编码为 Base64 格式 | :white_check_mark: | :white_check_mark: | +| verifyPSS | 使用PSS验签,返回字符串 | :white_check_mark: | :white_check_mark: | +| verifyPSSBytes | 使用PSS验签,返回字节 | :white_check_mark: | :white_check_mark: | +| verifyPKCS1v15 | 使用PKCS1v15验签,返回字符串 | :white_check_mark: | :white_check_mark: | +| verifyPKCS1v15Bytes | 使用PKCS1v15验签,返回字节 | :white_check_mark: | :white_check_mark: | +| generate | 生成随机的非对称密钥对 | :white_check_mark: | :white_check_mark: | +| convertJWKToPrivateKey | JWK格式字符串转换私钥 | :white_check_mark: | :x: | +| convertJWKToPublicKey | JWK格式字符串转换公钥 | :white_check_mark: | :x: | +| convertKeyPairToPKCS12 | 密钥对转换PKCS12格式字符串 | :white_check_mark: | :x: | +| convertPrivateKeyToJWK | 私钥转换为JWK格式字符串 | :white_check_mark: | :x: | +| convertPrivateKeyToPublicKey | 私钥转换为公钥 | :white_check_mark: | :x: | +| convertPublicKeyToJWK | 公钥转换为JWK格式字符串 | :white_check_mark: | :x: | +| convertPKCS12ToKeyPair | PKCS12格式字符串转换密钥对 | :white_check_mark: | :x: | diff --git a/flutter_rsa_ohos/analysis_options.yaml b/flutter_rsa_ohos/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5744c1cfbe77ae2daba29c74156c617b5f09b77 --- /dev/null +++ b/flutter_rsa_ohos/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/flutter_rsa_ohos/example/.gitignore b/flutter_rsa_ohos/example/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bb4b1310092b3e04b196e7a2778996d1c2e0bd6a --- /dev/null +++ b/flutter_rsa_ohos/example/.gitignore @@ -0,0 +1,46 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ +test/ +pubspec.lock + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/flutter_rsa_ohos/example/README.md b/flutter_rsa_ohos/example/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3e2afb917602f3646a4991423623f50c778d6d53 --- /dev/null +++ b/flutter_rsa_ohos/example/README.md @@ -0,0 +1,16 @@ +# flutter_rsa_ohos_example + +Demonstrates how to use the flutter_rsa_ohos plugin. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/flutter_rsa_ohos/example/analysis_options.yaml b/flutter_rsa_ohos/example/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61b6c4de17c96863d24279f06b85e01b6ebbdb34 --- /dev/null +++ b/flutter_rsa_ohos/example/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/flutter_rsa_ohos/example/fonts/Roboto/LICENSE.txt b/flutter_rsa_ohos/example/fonts/Roboto/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/flutter_rsa_ohos/example/fonts/Roboto/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Black.ttf b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Black.ttf new file mode 100644 index 0000000000000000000000000000000000000000..689fe5cb3c715f2944fec30e43ccb8a2b10625d3 Binary files /dev/null and b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Black.ttf differ diff --git a/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Bold.ttf b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d3f01ad245b628f386ac95786f53167038720eb2 Binary files /dev/null and b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Bold.ttf differ diff --git a/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Light.ttf b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Light.ttf new file mode 100644 index 0000000000000000000000000000000000000000..219063a578a486b7c00262057efcbc44ebab0eeb Binary files /dev/null and b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Light.ttf differ diff --git a/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Medium.ttf b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Medium.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1a7f3b0bba45b7470a4240c3ec67595eeeb02192 Binary files /dev/null and b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Medium.ttf differ diff --git a/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Regular.ttf b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2c97eeadffe1a34bd67d3ff1c3887fd53e22c2ca Binary files /dev/null and b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Regular.ttf differ diff --git a/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Thin.ttf b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Thin.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b74a4fd1a2ed1960da1d0f8f0e9b8d05a5819000 Binary files /dev/null and b/flutter_rsa_ohos/example/fonts/Roboto/Roboto-Thin.ttf differ diff --git a/flutter_rsa_ohos/example/lib/base64.dart b/flutter_rsa_ohos/example/lib/base64.dart new file mode 100644 index 0000000000000000000000000000000000000000..0b584bc1c13f9f7c67e3572214ff4b26e128209b --- /dev/null +++ b/flutter_rsa_ohos/example/lib/base64.dart @@ -0,0 +1,57 @@ +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class Base64 extends StatefulWidget { + const Base64({ + Key? key, + required this.title, + required PKCS12KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final PKCS12KeyPair keyPair; + final String title; + + @override + _Base64State createState() => _Base64State(); +} + +class _Base64State extends State { + String _encrypted = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Encode", + key: Key("encode"), + result: _encrypted, + onPressed: (controller) async { + var encrypted = await RSA.base64( + controller.text, + ); + setState(() { + _encrypted = encrypted; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/convert_jwt.dart b/flutter_rsa_ohos/example/lib/convert_jwt.dart new file mode 100644 index 0000000000000000000000000000000000000000..5ccabaaa81b718f6cf985eb2c1a9a14902575bc7 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/convert_jwt.dart @@ -0,0 +1,79 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class ConvertJWT extends StatefulWidget { + const ConvertJWT({ + Key? key, + required this.title, + required PKCS12KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final PKCS12KeyPair keyPair; + final String title; + + @override + _ConvertJWTState createState() => _ConvertJWTState(); +} + +class _ConvertJWTState extends State { + String _public = ""; + String _private = ""; + + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + ButtonWidget( + title: "To PrivateKey", + key: Key("private"), + result: _private, + onPressed: () async { + var converted = await RSA.convertPrivateKeyToJWK( + widget.keyPair.privateKey, + ); + var result = await RSA.convertJWKToPrivateKey(converted, ""); + setState(() { + _private = result; + }); + }, + ), + ButtonWidget( + title: "To PublicKey", + key: Key("public"), + result: _public, + onPressed: () async { + var converted = await RSA.convertPublicKeyToJWK( + widget.keyPair.publicKey, + ); + var result = await RSA.convertJWKToPublicKey(converted, ""); + setState(() { + _public = result; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/convert_keypair.dart b/flutter_rsa_ohos/example/lib/convert_keypair.dart new file mode 100644 index 0000000000000000000000000000000000000000..a5be35ac4db57b9e84b59da77632783ee4b5d688 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/convert_keypair.dart @@ -0,0 +1,64 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class ConvertKeyPair extends StatefulWidget { + const ConvertKeyPair({ + Key? key, + required this.title, + required PKCS12KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final PKCS12KeyPair keyPair; + final String title; + + @override + _ConvertKeyPairState createState() => _ConvertKeyPairState(); +} + +class _ConvertKeyPairState extends State { + String _pkcs12 = ""; + + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + ButtonWidget( + title: "To PKCS12", + key: Key("pkcs12"), + result: _pkcs12, + onPressed: () async { + var result = await RSA.convertKeyPairToPKCS12( + widget.keyPair.privateKey, + widget.keyPair.certificate, + password); + setState(() { + _pkcs12 = result; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/convert_private.dart b/flutter_rsa_ohos/example/lib/convert_private.dart new file mode 100644 index 0000000000000000000000000000000000000000..7da80e58616431ce069da6b1146527bc14318582 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/convert_private.dart @@ -0,0 +1,100 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class ConvertPrivate extends StatefulWidget { + const ConvertPrivate({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _ConvertPrivateState createState() => _ConvertPrivateState(); +} + +class _ConvertPrivateState extends State { + String _jwt = ""; + String _pkcs1 = ""; + String _pkcs8 = ""; + String _publicKey = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + ButtonWidget( + title: "To JWT", + key: Key("jwt"), + result: _jwt, + onPressed: () async { + var result = await RSA.convertPrivateKeyToJWK( + widget.keyPair.privateKey, + ); + setState(() { + _jwt = jsonEncode(result); + }); + }, + ), + ButtonWidget( + title: "To PKCS1", + key: Key("pkcs1"), + result: _pkcs1, + onPressed: () async { + var result = await RSA.convertPrivateKeyToPKCS1( + widget.keyPair.privateKey, + ); + setState(() { + _pkcs1 = result; + }); + }, + ), + ButtonWidget( + title: "To PKCS8", + key: Key("pkcs8"), + result: _pkcs8, + onPressed: () async { + var result = await RSA.convertPrivateKeyToPKCS8( + widget.keyPair.privateKey, + ); + setState(() { + _pkcs8 = result; + }); + }, + ), + ButtonWidget( + title: "To PublicKey", + key: Key("public-key"), + result: _publicKey, + onPressed: () async { + var result = await RSA.convertPrivateKeyToPublicKey( + widget.keyPair.privateKey, + ); + setState(() { + _publicKey = result; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/convert_public.dart b/flutter_rsa_ohos/example/lib/convert_public.dart new file mode 100644 index 0000000000000000000000000000000000000000..426256b85e1ac63c9df9f38b7fe806dcbaf22a4a --- /dev/null +++ b/flutter_rsa_ohos/example/lib/convert_public.dart @@ -0,0 +1,86 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class ConvertPublic extends StatefulWidget { + const ConvertPublic({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _ConvertPublicState createState() => _ConvertPublicState(); +} + +class _ConvertPublicState extends State { + String _jwt = ""; + String _pkcs1 = ""; + String _pkix = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + ButtonWidget( + title: "To JWT", + key: Key("jwt"), + result: _jwt, + onPressed: () async { + var result = await RSA.convertPublicKeyToJWK( + widget.keyPair.publicKey, + ); + setState(() { + _jwt = jsonEncode(result); + }); + }, + ), + ButtonWidget( + title: "To PKCS1", + key: Key("pkcs1"), + result: _pkcs1, + onPressed: () async { + var result = await RSA.convertPublicKeyToPKCS1( + widget.keyPair.publicKey, + ); + setState(() { + _pkcs1 = result; + }); + }, + ), + ButtonWidget( + title: "To PKIX", + key: Key("pkix"), + result: _pkix, + onPressed: () async { + var result = await RSA.convertPublicKeyToPKIX( + widget.keyPair.publicKey, + ); + setState(() { + _pkix = result; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_decrypt_oaep.dart b/flutter_rsa_ohos/example/lib/encrypt_decrypt_oaep.dart new file mode 100644 index 0000000000000000000000000000000000000000..0f1ce76af008d6ff35de5c404fa749cd4e20a5ef --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_decrypt_oaep.dart @@ -0,0 +1,77 @@ +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class EncryptAndDecryptOAEP extends StatefulWidget { + const EncryptAndDecryptOAEP({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _EncryptAndDecryptOAEPState createState() => _EncryptAndDecryptOAEPState(); +} + +class _EncryptAndDecryptOAEPState extends State { + String _encrypted = ""; + String _decrypted = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Encrypt", + key: Key("encrypt"), + result: _encrypted, + onPressed: (controller) async { + var encrypted = await RSA.encryptOAEP( + controller.text, + "", + Hash.SHA256, + widget.keyPair.publicKey, + ); + setState(() { + _encrypted = encrypted; + }); + }, + ), + ButtonWidget( + title: "Decrypt", + key: Key("decrypt"), + result: _decrypted, + onPressed: () async { + var decrypted = await RSA.decryptOAEP( + _encrypted, + "", + Hash.SHA256, + widget.keyPair.privateKey, + ); + setState(() { + _decrypted = decrypted; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_decrypt_oaep_bytes.dart b/flutter_rsa_ohos/example/lib/encrypt_decrypt_oaep_bytes.dart new file mode 100644 index 0000000000000000000000000000000000000000..d004dd1957314194a16f1841464a189007d6060a --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_decrypt_oaep_bytes.dart @@ -0,0 +1,80 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class EncryptAndDecryptOAEPBytes extends StatefulWidget { + const EncryptAndDecryptOAEPBytes({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _EncryptAndDecryptOAEPBytesState createState() => + _EncryptAndDecryptOAEPBytesState(); +} + +class _EncryptAndDecryptOAEPBytesState + extends State { + String _encrypted = ""; + String _decrypted = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Encrypt", + key: Key("encrypt"), + result: _encrypted, + onPressed: (controller) async { + var encrypted = await RSA.encryptOAEPBytes( + Uint8List.fromList(controller.text.codeUnits), + "1234", + Hash.SHA256, + widget.keyPair.publicKey, + ); + setState(() { + _encrypted = base64Encode(encrypted); + }); + }, + ), + ButtonWidget( + title: "Decrypt", + key: Key("decrypt"), + result: _decrypted, + onPressed: () async { + var decrypted = await RSA.decryptOAEPBytes( + base64Decode(_encrypted), + "1234", + Hash.SHA256, + widget.keyPair.privateKey, + ); + setState(() { + _decrypted = String.fromCharCodes(decrypted); + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_decrypt_pkcs.dart b/flutter_rsa_ohos/example/lib/encrypt_decrypt_pkcs.dart new file mode 100644 index 0000000000000000000000000000000000000000..4bb9186121e150b6f79344f6109adb002e661069 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_decrypt_pkcs.dart @@ -0,0 +1,73 @@ +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class EncryptAndDecryptPKCS extends StatefulWidget { + const EncryptAndDecryptPKCS({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _EncryptAndDecryptPKCSState createState() => _EncryptAndDecryptPKCSState(); +} + +class _EncryptAndDecryptPKCSState extends State { + String _encrypted = ""; + String _decrypted = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Encrypt", + key: Key("encrypt"), + result: _encrypted, + onPressed: (controller) async { + var encrypted = await RSA.encryptPKCS1v15( + controller.text, + widget.keyPair.publicKey, + ); + setState(() { + _encrypted = encrypted; + }); + }, + ), + ButtonWidget( + title: "Decrypt", + key: Key("decrypt"), + result: _decrypted, + onPressed: () async { + var decrypted = await RSA.decryptPKCS1v15( + _encrypted, + widget.keyPair.privateKey, + ); + setState(() { + _decrypted = decrypted; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_decrypt_pkcs_bytes.dart b/flutter_rsa_ohos/example/lib/encrypt_decrypt_pkcs_bytes.dart new file mode 100644 index 0000000000000000000000000000000000000000..157a809d2fd0dd9f867692ac5c7dba059c352184 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_decrypt_pkcs_bytes.dart @@ -0,0 +1,76 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class EncryptAndDecryptPKCSBytes extends StatefulWidget { + const EncryptAndDecryptPKCSBytes({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _EncryptAndDecryptPKCSBytesState createState() => + _EncryptAndDecryptPKCSBytesState(); +} + +class _EncryptAndDecryptPKCSBytesState + extends State { + String _encrypted = ""; + String _decrypted = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Encrypt", + key: Key("encrypt"), + result: _encrypted, + onPressed: (controller) async { + var encrypted = await RSA.encryptPKCS1v15Bytes( + Uint8List.fromList(controller.text.codeUnits), + widget.keyPair.publicKey, + ); + setState(() { + _encrypted = base64Encode(encrypted); + }); + }, + ), + ButtonWidget( + title: "Decrypt", + key: Key("decrypt"), + result: _decrypted, + onPressed: () async { + var decrypted = await RSA.decryptPKCS1v15Bytes( + base64Decode(_encrypted), + widget.keyPair.privateKey, + ); + setState(() { + _decrypted = String.fromCharCodes(decrypted); + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_decrypt_private.dart b/flutter_rsa_ohos/example/lib/encrypt_decrypt_private.dart new file mode 100644 index 0000000000000000000000000000000000000000..987ad9568b085f14f15c054b627cf389613d4172 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_decrypt_private.dart @@ -0,0 +1,74 @@ +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class EncryptAndDecryptPrivate extends StatefulWidget { + const EncryptAndDecryptPrivate({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _EncryptAndDecryptPrivateState createState() => _EncryptAndDecryptPrivateState(); +} + +class _EncryptAndDecryptPrivateState extends State { + String _encrypted = ""; + String _decrypted = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + ButtonWidget( + title: "Encrypt", + key: Key("encrypt"), + result: _encrypted, + onPressed: () async { + var encrypted = await RSA.encryptPrivateKey( + widget.keyPair.privateKey, + password, + PEMCipher.AES256, + ); + setState(() { + _encrypted = encrypted; + }); + }, + ), + ButtonWidget( + title: "Decrypt", + key: Key("decrypt"), + result: _decrypted, + onPressed: () async { + var decrypted = await RSA.decryptPrivateKey( + _encrypted, + password, + ); + setState(() { + _decrypted = decrypted; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_sign_pkcs.dart b/flutter_rsa_ohos/example/lib/encrypt_sign_pkcs.dart new file mode 100644 index 0000000000000000000000000000000000000000..9e9ca65cc137c5d8e8fced663f9bdd70524e7ac1 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_sign_pkcs.dart @@ -0,0 +1,78 @@ +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class SignAndVerifyPKCS extends StatefulWidget { + const SignAndVerifyPKCS({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _SignAndVerifyPKCSState createState() => _SignAndVerifyPKCSState(); +} + +class _SignAndVerifyPKCSState extends State { + String _signed = ""; + String _text = ""; + String _valid = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Sign", + key: Key("sign"), + result: _signed, + onPressed: (controller) async { + var result = await RSA.signPKCS1v15( + controller.text, + Hash.SHA256, + widget.keyPair.privateKey, + ); + setState(() { + _text = controller.text; + _signed = result; + }); + }, + ), + ButtonWidget( + title: "Verify", + key: Key("verify"), + result: _valid, + onPressed: () async { + var result = await RSA.verifyPKCS1v15( + _signed, + _text, + Hash.SHA256, + widget.keyPair.publicKey, + ); + setState(() { + _valid = result ? "VALID" : "INVALID"; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_sign_pkcs_bytes.dart b/flutter_rsa_ohos/example/lib/encrypt_sign_pkcs_bytes.dart new file mode 100644 index 0000000000000000000000000000000000000000..a23d1d25440c32314423a0fe9b646c062bdb4421 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_sign_pkcs_bytes.dart @@ -0,0 +1,79 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class SignAndVerifyPKCSBytes extends StatefulWidget { + const SignAndVerifyPKCSBytes({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _SignAndVerifyPKCSBytesState createState() => _SignAndVerifyPKCSBytesState(); +} + +class _SignAndVerifyPKCSBytesState extends State { + String _signed = ""; + String _text = ""; + String _valid = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Sign", + key: Key("sign"), + result: _signed, + onPressed: (controller) async { + var result = await RSA.signPKCS1v15Bytes( + Uint8List.fromList(controller.text.codeUnits), + Hash.SHA256, + widget.keyPair.privateKey, + ); + setState(() { + _text = controller.text; + _signed = base64Encode(result); + }); + }, + ), + ButtonWidget( + title: "Verify", + key: Key("verify"), + result: _valid, + onPressed: () async { + var result = await RSA.verifyPKCS1v15Bytes( + base64Decode(_signed), + Uint8List.fromList(_text.codeUnits), + Hash.SHA256, + widget.keyPair.publicKey, + ); + setState(() { + _valid = result ? "VALID" : "INVALID"; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_sign_pss.dart b/flutter_rsa_ohos/example/lib/encrypt_sign_pss.dart new file mode 100644 index 0000000000000000000000000000000000000000..90a4c7817b650f7ead4d923de292907828a2873d --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_sign_pss.dart @@ -0,0 +1,80 @@ +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class SignAndVerifyPSS extends StatefulWidget { + const SignAndVerifyPSS({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _SignAndVerifyPSSState createState() => _SignAndVerifyPSSState(); +} + +class _SignAndVerifyPSSState extends State { + String _signed = ""; + String _text = ""; + String _valid = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Sign", + key: Key("sign"), + result: _signed, + onPressed: (controller) async { + var result = await RSA.signPSS( + controller.text, + Hash.SHA256, + SaltLength.AUTO, + widget.keyPair.privateKey, + ); + setState(() { + _text = controller.text; + _signed = result; + }); + }, + ), + ButtonWidget( + title: "Verify", + key: Key("verify"), + result: _valid, + onPressed: () async { + var result = await RSA.verifyPSS( + _signed, + _text, + Hash.SHA256, + SaltLength.AUTO, + widget.keyPair.publicKey, + ); + setState(() { + _valid = result ? "VALID" : "INVALID"; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/encrypt_sign_pss_bytes.dart b/flutter_rsa_ohos/example/lib/encrypt_sign_pss_bytes.dart new file mode 100644 index 0000000000000000000000000000000000000000..1e6d001f8f9a12509efe69e1cd858c0477db7e11 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/encrypt_sign_pss_bytes.dart @@ -0,0 +1,81 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class SignAndVerifyPSSBytes extends StatefulWidget { + const SignAndVerifyPSSBytes({ + Key? key, + required this.title, + required KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final KeyPair keyPair; + final String title; + + @override + _SignAndVerifyPSSBytesState createState() => _SignAndVerifyPSSBytesState(); +} + +class _SignAndVerifyPSSBytesState extends State { + String _signed = ""; + String _text = ""; + String _valid = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Sign", + key: Key("sign"), + result: _signed, + onPressed: (controller) async { + var result = await RSA.signPSSBytes( + Uint8List.fromList(controller.text.codeUnits), + Hash.SHA256, + SaltLength.AUTO, + widget.keyPair.privateKey, + ); + setState(() { + _text = controller.text; + _signed = base64Encode(result); + }); + }, + ), + ButtonWidget( + title: "Verify", + key: Key("verify"), + result: _valid, + onPressed: () async { + var result = await RSA.verifyPSSBytes( + base64Decode(_signed), + Uint8List.fromList(_text.codeUnits), + Hash.SHA256, + SaltLength.AUTO, + widget.keyPair.publicKey, + ); + setState(() { + _valid = result ? "VALID" : "INVALID"; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/generate.dart b/flutter_rsa_ohos/example/lib/generate.dart new file mode 100644 index 0000000000000000000000000000000000000000..60567f51ccbc7e2d80f2993a8b2caf2c6536230f --- /dev/null +++ b/flutter_rsa_ohos/example/lib/generate.dart @@ -0,0 +1,54 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class Generate extends StatefulWidget { + const Generate({ + Key? key, + required this.title, + required PKCS12KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final PKCS12KeyPair keyPair; + final String title; + + @override + _GenerateState createState() => _GenerateState(); +} + +class _GenerateState extends State { + KeyPair _keyPair = KeyPair("", ""); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + ButtonWidget( + title: "Generate", + key: Key("action"), + result: _keyPair.privateKey + _keyPair.publicKey, + onPressed: () async { + var keyPair = await RSA.generate(2048); + setState(() { + _keyPair = keyPair; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/hash.dart b/flutter_rsa_ohos/example/lib/hash.dart new file mode 100644 index 0000000000000000000000000000000000000000..d58d2ed7c962340666cb27714c2e7db6c8f304fb --- /dev/null +++ b/flutter_rsa_ohos/example/lib/hash.dart @@ -0,0 +1,54 @@ +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; +import 'package:flutter_rsa_ohos_example/main.dart'; +import 'package:flutter_rsa_ohos_example/shared/button_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/input_widget.dart'; +import 'package:flutter_rsa_ohos_example/shared/title_widget.dart'; + +class HashExample extends StatefulWidget { + const HashExample({ + Key? key, + required this.title, + required PKCS12KeyPair keyPair, + }) : keyPair = keyPair, + super(key: key); + + final PKCS12KeyPair keyPair; + final String title; + + @override + _HashExampleState createState() => _HashExampleState(); +} + +class _HashExampleState extends State { + String _encrypted = ""; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Card( + child: Column( + children: [ + TitleWidget(widget.title), + InputWidget( + title: "Encode", + key: Key("encode"), + result: _encrypted, + onPressed: (controller) async { + var encrypted = await RSA.hash(controller.text, Hash.SHA512); + setState(() { + _encrypted = encrypted; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/main.dart b/flutter_rsa_ohos/example/lib/main.dart new file mode 100644 index 0000000000000000000000000000000000000000..61b85bb6e82ee06e18a135f6c23c36cd72ed5e6d --- /dev/null +++ b/flutter_rsa_ohos/example/lib/main.dart @@ -0,0 +1,252 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; +import 'package:flutter_rsa_ohos_example/base64.dart'; +import 'package:flutter_rsa_ohos_example/convert_jwt.dart'; +import 'package:flutter_rsa_ohos_example/convert_keypair.dart'; +import 'package:flutter_rsa_ohos_example/convert_private.dart'; +import 'package:flutter_rsa_ohos_example/convert_public.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_decrypt_oaep.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_decrypt_private.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_decrypt_oaep_bytes.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_decrypt_pkcs.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_decrypt_pkcs_bytes.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_sign_pkcs.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_sign_pkcs_bytes.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_sign_pss.dart'; +import 'package:flutter_rsa_ohos_example/encrypt_sign_pss_bytes.dart'; +import 'package:flutter_rsa_ohos_example/generate.dart'; +import 'package:flutter_rsa_ohos_example/hash.dart'; + +const password = '123456789'; +const pkcs12 = +'''MIIQSQIBAzCCEA8GCSqGSIb3DQEHAaCCEAAEgg/8MIIP+DCCBi8GCSqGSIb3DQEH +BqCCBiAwggYcAgEAMIIGFQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQI/pTm +UKFwK/UCAggAgIIF6N5rjkv/eidrXYlkrkyl2EBNfK8hQU+cJt0lkLt6zVC+ddNW +THJW4R98rhFGqYvSRHP13H65Pq+zG8nFu4WyRog3qO/rOcQPNCFeJQ1k1RUa7HSx +Ugjki8s7WG0+EsuA39jqZDrVDdaU2gWrgR9Oj5d5/zITYu7Rr37I+S1es9otUBus +YPd/YaNwtWyLuZJikDjQuMxtHEzyRshu0fylDloTFLGSmdQQR2DxQDWffoi3Hq1G +a7KoDW9kgqZPAyOOeRf24Y3dqNYJbJ9Sk5w5GNQldGy++LH26fhcu+/fXMxjq5+9 +0Z2mJguDGbKf4JtAXEaFQGE7UQFULjdh4dmfl45Wv4rhfyst+BA6wvW3EClJ3/7a +/pmtM0SmiGmIxKO3AYsqCljkRJvpE5Ph5SmsX8HJQBMX0AkYzQI9KmSuCyuze64y +4VmW0ZLxfL/rmJn1UIywaznQcE/f2eN52K39eo96P1rY19hbTx+b+pSTnpFnxf8e +vkbVvLKLug0ifZcw+cIF+AeUS/SRVA06icC6ul2vdAsc78tlSXkVBzV/dj1ohIU6 +i3atO7Lz+OIHRlh02IVtCW/Pwgm44kmxYu6ZM3P1uQjVympBkelD/4wBLdZMCUwP +4z9wGD9gQUVzxspwL3d9NHRdd1JLVFxoLG0kmt1zj2EEMTyPuHtGMyzhRRM6qDu1 +1JUTDgyO1dFHmWqBbWyrPe1gAaGvZUaMrmv2ekvncOgvMZEIbvxEVf3nH49lBJ5h +qBNBHDPgIjQcrpF4ym5ghWq/fmoH27Wn5wKyJkfs54TLy7AWM125zqINntTN89Mf +IcqLLBumlgRfy0QnsZiAzeQf6ELrrMUw1LqV9PPwTGlcqk9CfVI2jaDYGSKtkbrr +CbeNmElF9wU/kmMSzEsVqfRPfaWMNkpuIek330lEkHHBbZ38kaXsJcXcAQ1swoc9 +UegtOKX1g0wU4+fMIX43tlzIz1RmNqjQXBlLBFqc++JHwqGW1bhrNOJqvAKZhGU0 +QPCQNYxh5waqWdGUa5P+kWAAlIOd24aMohlKIYYVJXkFbZhDcDhY85FUeEP5AT5L +tOKCtE7dI6LK+m2nR+yw0zwokqmfwqh3IQJYOirZc2BYa8VDYVj1gaHsGcsKCE1g +6lzvKvIUzRRIWc/xvzOfD6ywD9/MTBkgGAYokocLkd+BFcrtJkWt0VzVCj32t7G7 +PgPxjns5xSyDRAR8Q9UGyCnj4RrRsuLyR+B/swFdTfRLaVNFEHNxZnOBolvxzcNE +sF2PV+3ZRMQE/8FCbk3z9vG/LMey+Z2TLtB4HA0uzGC+YrnFsIBFCksfIaDHzhrg +Wm+D4tNwEDGnT31f/beyIf3FWVcaogxQYD//s4k3ldTc46h+hJenMhPWgq1lvIyK +VOHveA5AzGiOTdBBqn8eoQsHnP8d7axoYu2Es1Yh//5jBQU0v6WLnzlirj+t24s/ +1YqsXyJXDN0jlMQ6+lVx6KOWUGjbuZtGuOfY6rwzv9TDq2hPZLFmCANLlJcahDgZ +ipvrGIO4xP7tlTf49ASckbqLB3CF6Fe4/FhK7teo4TEXEjilHlacIiELUUo7Jo6h ++6r1fsv1VplBHyhF1zzWKX0RCytx8dw5Py7uBxWz4aSTjmg6k9SLri1KMZRvGsp/ +sVUarJ6sNRhGk86gWpgE0uH3q8ZBGrs0roF1YMGJHdtqPT7sdulhuvhDHS8idRIR +mzWG3yiFvEcbSydPyQriTdENHbmf+faRkTMucOaac5bqdazqDgKHtzPiH0+5ruNA +xlSiInoI8w8Xh0XRlL2eZ3j0OyOftYzj+xCdkhGj2nYXecvlaPBhs7ZIuvltn2Oe +6zI2fudtiOVSo6Eb98h8v9TpM1SS4RL7BnCnPkhX3XNCu3H5D10YerGlLjqwX3ZQ +WpgBTRhpC2A8TEFGZBu/GHAvR/4sVSkPW7Nw6TBcCNVThrnyM4o7bDCdmlCBXFmr +jz5O5C2e8/xCqvmzL+EG0/iny+5p3si6xAnPleniUyiS6IdybTCCCcEGCSqGSIb3 +DQEHAaCCCbIEggmuMIIJqjCCCaYGCyqGSIb3DQEMCgECoIIJbjCCCWowHAYKKoZI +hvcNAQwBAzAOBAiINWiWDO9TpgICCAAEgglItWrFwv6mt10g76SgnfbqUnz3glB8 +vBUk5zouqR+43/fSF0hK0LhRF5vsnq8U2jwXTYxQYguJy6MjpZl1wNZ42kdWMCHF +ci8EYn9+4xd+tSakuilJmEJ4hybD3GRabcslivurd/9sGYpQ9oPWLbuEsoJJC83y +qn6YQL6DSbdb1hctndEp2kuLK7Xha1pe1T99vrgieGeELV1MCitR2tGR4o38UjBb +YUxI8wXtjSFWI+59szwdwnOTi8jBBgxyD0mzfAe7jnwuX61Kctj97UBKp353jtUq +flOVqqCkLq+yvpId/361CL3+k1Gi6xMfFUH+GwBJZcCc2Ue/wsoWlFnA9Ck2+ROt +cvS9Q94otkOPkscGU92sna6Oz4ESGgSTyc0HumuApbq33t6+yQKZtV/zds48IeQ1 +ZaDqCtYhycr80CSveHuyI12ExNRT56AFTEk9oP7OpCu3BhqECDPJ+tF+TyGBjPf8 +MQyshXPaGkf/gzpkcK21ZCKDZgbFkt07WzmjrIn5JvpO+spxKxXSDMe4DGeA3fkT +VVUwumJl1y/8uHs9MQmL7jZgicoCap75lSuR84zMnF0zRbmNK33ujHCpyMZ/F/Ys +tVR9SwcdJCa30nckkWUAMhKTa5UI856aR9Qtwu9384ggrtXvqz1uUy3MkAluOPX+ +Ce4RWpUO87qEk2oOwN6lPVBlRnUe9VbmRlTBTeLgsF7lXLZ820pQkuZAql1XAFa0 +FzjHw3f846XFlt3sFjkgBlLo/x8zVQ7HX9S+3aBiGZO0eY1T5HeTjiDOEuxDa0ZY +CbsD7NuFiZud06m7BoiOVxiFAuq3RE15NC86f8zEfP2Resfr/LGLeeSqpIzwvCTI +kUczHPoTtHQWEdo1M8/gAYhavv9dYz1c9uvI8ZQcnc7S4X7fA9JFXi2bJQrWKOJr +x4wFAj3nUH6PaC8/Lg74cJzTqy7STEoHrlQbDMLZNAO974AJGDm7glSw4XwQO5h+ +euL4J7vTXx+WbnRT1ymHfvUZEydqH0DEjLkicut65tbvJZAm6M3tbBCP24myWUHR +tbw7BZQKczt/AxmgotC5Nt8uflzSfQ2n2POTwxOrvWcd660rrumkVANCMas5WiQD +2zlxMBjiNW3JA2I/ytivyYKGampECZEi3Zcl3FuBTFBJkSbeShfAA8wWPYxiVn/M +ybdT24uQThtQEvpPOkxyszHB7L6nnQ7a/eOjMPUc+oe2cfTbupU2ZtArSxZm7vMn +B1gyFxHIIkFlp1RzYVtYoQcHN9XDRc9lanCKQUn6Rrqq6KoQN/rXf6VRvoWG23tg +SlEBC73sd/28mcbSyMYDB18zmbZnzMazSUzndDpgv+5qypcslRq1fSfAK3dKUOI8 +7kPpKxRtq5HvuiGMqLG9xzdlJpqCUJ3PAhsYNmU2uFVqsaRLzOBNk0e7M0H0NAr1 +4YuXh6ZPjx65ZBJRLRwl7vNEgbWT0QYb9e2Hr7sxuWvjFEeac6N43PXOvMVEBNFc +3Y+ZeMV4K6833H8u9WMKRIHOUNRXXaAWIZvK2qsdyMV/y+wfK9L9GTdDcXFJg6xJ +KNUjcz6p3TLsEf2l8qG2Ddb1/0dfMBx8qE9Hfw9MBPKYbkYmJECStLLfPZ04GQ4s +yS+niHKvvMnsJHVfz18zcnnaA9EIg3FCsvs5TuVShMWkATrbBuhUbpmiU6iyTjtI +esXg46yXFOeam547fXDOYXUTnp+i8SK4ovFOwZ0KbjK0cr/WrbGla59SSpmEW80u +JeOl/icVuI2A1VclLmQt5ZKeMzKUBbG5ontVNTsOeXylAdG/cC13UiXVFjt029YV +XwKEjIzZE1++pa1FZrkHJvz/zkE6fnTUlSN52eIP6IMQWfIEemPUTtq217tEgicX +PgSig9oCL4ZX2dekm8a4xVzLu/e5v6BKHLIY6AdfwWXxYvxQlX6PVAybDT01eRMS +7LErjuY+3jB/o9Mptta777iRFAL/aohDd4zKBNVKRPCdhDXA8+n/OSQ3tEBOM32X +YOOKntunjdDe3+dachRp3U5SIfaympX92bAsN2USNooAfjN2YbiMd2coO/SrKv6Q +86Wz984ojyArA+/bEtoi91C7EAim7lo1LHeEFj8J8RC9AqYKIo0OeNjIjgDAx+Su +kkWt+N0zNgumwXfeODb/THkJkgfv+OrlexwUtvrvT6gh8RHWETByxUVCu6sYqQMC +YIP9ztSszuIhEvHrMII+lf98E1aGM5T3L/VQBmO4DEDqxrQ38r+7XPAK4uSXyKjg +mx+cIp5KohrlKgXeVg8aZvGLCDz4LHqhfZh6O6xTZM2uaR4iM00ZPEpPnSzTlZvg +Otv7rWjn7eP27HpJfNQMEKRRftxx1FOwBHCcrtMyU5x5cb2Qt7rkIMWTroInLubt +wCwat48j2FzDejxGxWyX30Bi6BH0Un79GC3TH4PkXaBwquBLSwdQjCUGUgUp83l4 +C3zXH8m1TuPgQ6pkplS0nNsjRVNHSQo94AbkmwuLEyEDSAUhC3ZW2tkQ9sj4tE7v +dUCZf4Ngl6bqjQdUNCKMaHYqzfg6ndt+al3OwMvgmIhG6D8z0yhj7sdJA7Ioj2q9 +kwdh9/Y/hglGTEUiHYl+Yv9MXBkxYxrofEjMToR8DRYgdJlTyuMBZpf52mHmE/ob +XLezyV5/CShtri34m5mauzsg7rih/tOQ5iYkqV/kcIvEqq9HeJQRteWHSkNSO4Df +VX0FWGClPVBLT+kzlWXT1t6yswe1Cdo/KQeNBISbp7SbGX/ZhSbR1swbme7I6Iq8 +NETOlLa49/aCrfTnpU8c//xxhedgTMyO30qRgUgX7BqniEU0/WJsI156DSedhcVh +DGVm4O54xJ09koguBo/4BP6rs0Vr3TqXzpq0npUYFE0UuxtECHnB6iyd7he/2inf +kn/No2BMDI0D005rxV6i8h1psk8wv6ACwZhX6L6/QjLP2PzM5zxM6VTsWyuUpN1t +cQ5QDZ4QaUaXRszyZ+xd7arJUCWTJkqZifLvB1WCZ0J28Jg5Bbd+fW/HKNlpB9vT +1bwsrTrXoiG+w70gTURjgRDgz9kJAGvHtqQuwe99SiGtaigdZ2ntTeplNjzA+iV6 +d4k6nehNbjrrhTDkeV4i7kRFjDQRQn8dX1XrVng3c1w4tJI46J82E1re1dCw9eU5 +SqLMMSUwIwYJKoZIhvcNAQkVMRYEFMlOPeNFP3dsXCHkZzNfcbC+SIwiMDEwITAJ +BgUrDgMCGgUABBQ9GTbjyC/z9oi+bg8R3kdod+2+XQQINXgTTMTGIPkCAggA'''; + +void main() { + if (!kIsWeb && (Platform.isLinux || Platform.isWindows)) { + debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia; + } + + runApp(new MyApp()); +} + +class MyApp extends StatefulWidget { + @override + _MyAppState createState() => _MyAppState(); +} + +class _MyAppState extends State { + PKCS12KeyPair _pkcs12KeyPair = PKCS12KeyPair("", "", ""); + KeyPair _keyPair = KeyPair("", ""); + + @override + void initState() { + super.initState(); + convertKey(); + } + + void convertKey() async { + try { + if(Platform.operatingSystem == 'ohos') { + var data = await RSA.generate(2048); + + setState(() { + _keyPair = data; + }); + return; + } + var data = await RSA.convertPKCS12ToKeyPair(pkcs12, password); + setState(() { + _pkcs12KeyPair = data; + }); + } catch (e) { + print('fast_rsa:: ' + e.toString()); + } + } + + @override + void dispose() { + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: const Text('RSA example app'), + ), + body: ListView( + key: Key("list"), + children: [ + EncryptAndDecryptOAEP( + title: "Encrypt and Decrypt OAEP", + keyPair: _keyPair, + key: Key("encrypt-oaep"), + ), + EncryptAndDecryptOAEPBytes( + title: "Encrypt and Decrypt OAEP Bytes", + keyPair: _keyPair, + key: Key("encrypt-oaep-bytes"), + ), + EncryptAndDecryptPKCS( + title: "Encrypt and Decrypt PKCS1v15", + keyPair: _keyPair, + key: Key("encrypt-pkcs"), + ), + EncryptAndDecryptPKCSBytes( + title: "Encrypt and Decrypt PKCS1v15 Bytes", + keyPair: _keyPair, + key: Key("encrypt-pkcs-bytes"), + ), + SignAndVerifyPSS( + title: "Sign and Verify PSS", + keyPair: _keyPair, + key: Key("sign-pss"), + ), + SignAndVerifyPSSBytes( + title: "Sign and Verify PSS Bytes", + keyPair: _keyPair, + key: Key("sign-pss-bytes"), + ), + SignAndVerifyPKCS( + title: "Sign and Verify PKCS", + keyPair: _keyPair, + key: Key("sign-pkcs"), + ), + SignAndVerifyPKCSBytes( + title: "Sign and Verify PKCS Bytes", + keyPair: _keyPair, + key: Key("sign-pkcs-bytes"), + ), + Base64( + title: "Base64", + keyPair: _pkcs12KeyPair, + key: Key("base64"), + ), + HashExample( + title: "Hash", + keyPair: _pkcs12KeyPair, + key: Key("hash"), + ), + Generate( + title: "Generate", + keyPair: _pkcs12KeyPair, + key: Key("generate"), + ), + ConvertPrivate( + title: "Convert PrivateKey", + keyPair: _keyPair, + key: Key("convert-private"), + ), + ConvertPublic( + title: "Convert PublicKey", + keyPair: _keyPair, + key: Key("convert-public"), + ), + ConvertJWT( + title: "Convert JWT", + keyPair: _pkcs12KeyPair, + key: Key("convert-jwt"), + ), + ConvertKeyPair( + title: "Convert KeyPair", + keyPair: _pkcs12KeyPair, + key: Key("convert-keypair"), + ), + ], + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/main_desktop.dart b/flutter_rsa_ohos/example/lib/main_desktop.dart new file mode 100644 index 0000000000000000000000000000000000000000..7958c72e76df486e2127dbe367e25c9dfebbeef1 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/main_desktop.dart @@ -0,0 +1,7 @@ +import 'main.dart' as original_main; +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; + +void main() { + RSA.bindingEnabled = false; + original_main.main(); +} diff --git a/flutter_rsa_ohos/example/lib/shared/button_widget.dart b/flutter_rsa_ohos/example/lib/shared/button_widget.dart new file mode 100644 index 0000000000000000000000000000000000000000..5104479f47f88c7deca4c7747b0a9c8c9c31b27b --- /dev/null +++ b/flutter_rsa_ohos/example/lib/shared/button_widget.dart @@ -0,0 +1,54 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +class ButtonWidget extends StatefulWidget { + const ButtonWidget({ + Key? key, + required this.result, + required String title, + required Function onPressed, + }) : onPressed = onPressed, + title = title, + super(key: key); + + final Function onPressed; + final String title; + final String result; + + @override + _ButtonWidgetState createState() => _ButtonWidgetState(); +} + +class _ButtonWidgetState extends State { + bool _loading = true; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Column( + children: [ + ElevatedButton( + child: Text(widget.title), + onPressed: () async { + await widget.onPressed(); + setState(() { + _loading = false; + }); + }, + key: Key("button"), + ), + (_loading) + ? Text( + widget.result, + key: Key("loading"), + ) + : Text( + widget.result, + key: Key("result"), + ) + ], + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/shared/input_widget.dart b/flutter_rsa_ohos/example/lib/shared/input_widget.dart new file mode 100644 index 0000000000000000000000000000000000000000..e7aa4b514e4d078984d45754e091a5678ae1a089 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/shared/input_widget.dart @@ -0,0 +1,78 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +class InputWidget extends StatefulWidget { + const InputWidget({ + Key? key, + required this.result, + required String title, + required Function(TextEditingController) onPressed, + }) : onPressed = onPressed, + title = title, + super(key: key); + + final Function(TextEditingController) onPressed; + final String title; + final String result; + + @override + _InputWidgetState createState() => _InputWidgetState(); +} + +class _InputWidgetState extends State { + final _controller = TextEditingController(); + FocusNode? _focusNode; + bool _loading = true; + + @override + void initState() { + super.initState(); + _focusNode = FocusNode(); + _controller.text = ""; + } + + @override + void dispose() { + _focusNode!.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(10), + child: Column( + children: [ + TextField( + autofocus: false, + focusNode: _focusNode, + decoration: InputDecoration(labelText: "Message"), + controller: _controller, + key: Key("message"), + ), + ElevatedButton( + child: Text(widget.title), + onPressed: () async { + _focusNode!.unfocus(); + await widget.onPressed(_controller); + setState(() { + _loading = false; + }); + }, + key: Key("button"), + ), + (_loading) + ? Text( + widget.result, + key: Key("loading"), + ) + : Text( + widget.result, + key: Key("result"), + ) + ], + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/lib/shared/title_widget.dart b/flutter_rsa_ohos/example/lib/shared/title_widget.dart new file mode 100644 index 0000000000000000000000000000000000000000..b9bd8da56719d1cceb7ae685891a50fac5b0c616 --- /dev/null +++ b/flutter_rsa_ohos/example/lib/shared/title_widget.dart @@ -0,0 +1,23 @@ +import 'package:flutter/cupertino.dart'; + +class TitleWidget extends StatelessWidget { + const TitleWidget( + this.title, { + Key? key, + }) : super(key: key); + + final String title; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(top: 10), + child: Text( + title, + style: TextStyle( + fontSize: 20, + ), + ), + ); + } +} diff --git a/flutter_rsa_ohos/example/ohos/.gitignore b/flutter_rsa_ohos/example/ohos/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6ca13b3170eec5dd5ac5ad7f1c4dd0118845f473 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/.gitignore @@ -0,0 +1,19 @@ +/node_modules +/oh_modules +/local.properties +/.idea +**/build +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +**/.test +*.har +**/BuildProfile.ets +**/oh-package-lock.json5 + +**/src/main/resources/rawfile/flutter_assets/ +**/libs/arm64-v8a/libapp.so +**/libs/arm64-v8a/libflutter.so +**/libs/arm64-v8a/libvmservice_snapshot.so diff --git a/flutter_rsa_ohos/example/ohos/AppScope/app.json5 b/flutter_rsa_ohos/example/ohos/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..6d20d33c958918d45f9ceff68a2608b38146eae8 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/AppScope/app.json5 @@ -0,0 +1,10 @@ +{ + "app": { + "bundleName": "com.example.flutter_rsa_ohos_example", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/AppScope/resources/base/element/string.json b/flutter_rsa_ohos/example/ohos/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..4e03a70f47a2d6d00b967e8c3155759791cfcc73 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "flutter_rsa_ohos_example" + } + ] +} diff --git a/flutter_rsa_ohos/example/ohos/AppScope/resources/base/media/app_icon.png b/flutter_rsa_ohos/example/ohos/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/flutter_rsa_ohos/example/ohos/AppScope/resources/base/media/app_icon.png differ diff --git a/flutter_rsa_ohos/example/ohos/build-profile.json5 b/flutter_rsa_ohos/example/ohos/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..1d12140d202702d7c73d64f1b291fe5c45a660ce --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/build-profile.json5 @@ -0,0 +1,27 @@ +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/.gitignore b/flutter_rsa_ohos/example/ohos/entry/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2795a1c5b1fe53659dd1b71d90ba0592eaf7e043 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/.gitignore @@ -0,0 +1,7 @@ + +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/build-profile.json5 b/flutter_rsa_ohos/example/ohos/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..633d360fbc91a3186a23b66ab71b27e5618944cb --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/build-profile.json5 @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "apiType": 'stageMode', + "buildOption": { + }, + "targets": [ + { + "name": "default", + "runtimeOS": "HarmonyOS" + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/hvigorfile.ts b/flutter_rsa_ohos/example/ohos/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..894fc15c6b793f085e6c8506e43d719af658e8ff --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/hvigorfile.ts @@ -0,0 +1,17 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +export { hapTasks } from '@ohos/hvigor-ohos-plugin'; diff --git a/flutter_rsa_ohos/example/ohos/entry/oh-package.json5 b/flutter_rsa_ohos/example/ohos/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..18a109fa6035fa233721bc7ce4a2b7db8391acb7 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/oh-package.json5 @@ -0,0 +1,12 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + "flutter_rsa_ohos": "file:../har/flutter_rsa_ohos.har", + "integration_test": "file:../har/integration_test.har" + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/ets/entryability/EntryAbility.ets b/flutter_rsa_ohos/example/ohos/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..8bc48be8773196f34cccb15cf517f87f5c6b94d2 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,24 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { FlutterAbility, FlutterEngine } from '@ohos/flutter_ohos'; +import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant'; + +export default class EntryAbility extends FlutterAbility { + configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + GeneratedPluginRegistrant.registerWith(flutterEngine) + } +} diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/ets/pages/Index.ets b/flutter_rsa_ohos/example/ohos/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..1125f9fdd95f4310a182c1c9e3680f37f73686c9 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import common from '@ohos.app.ability.common'; +import { FlutterPage } from '@ohos/flutter_ohos' + +let storage = LocalStorage.getShared() +const EVENT_BACK_PRESS = 'EVENT_BACK_PRESS' + +@Entry(storage) +@Component +struct Index { + private context = getContext(this) as common.UIAbilityContext + @LocalStorageLink('viewId') viewId: string = ""; + + build() { + Column() { + FlutterPage({ viewId: this.viewId }) + } + } + + onBackPress(): boolean { + this.context.eventHub.emit(EVENT_BACK_PRESS) + return true + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets b/flutter_rsa_ohos/example/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets new file mode 100644 index 0000000000000000000000000000000000000000..0af1f2afe5df1a48c59ab2710238d3507faf99bf --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets @@ -0,0 +1,28 @@ +import { FlutterEngine, Log } from '@ohos/flutter_ohos'; +import FlutterRsaOhosPlugin from 'flutter_rsa_ohos'; +import IntegrationTestPlugin from 'integration_test'; + +/** + * Generated file. Do not edit. + * This file is generated by the Flutter tool based on the + * plugins that support the Ohos platform. + */ + +const TAG = "GeneratedPluginRegistrant"; + +export class GeneratedPluginRegistrant { + + static registerWith(flutterEngine: FlutterEngine) { + try { + flutterEngine.getPlugins()?.add(new FlutterRsaOhosPlugin()); + flutterEngine.getPlugins()?.add(new IntegrationTestPlugin()); + } catch (e) { + Log.e( + TAG, + "Tried to register plugins with FlutterEngine (" + + flutterEngine + + ") failed."); + Log.e(TAG, "Received exception while registering", e); + } + } +} diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/module.json5 b/flutter_rsa_ohos/example/ohos/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..7bbf78b18f39991b1404061c7437538c7d532bb7 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/module.json5 @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "requestPermissions": [ + {"name" : "ohos.permission.INTERNET"}, + ] + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/element/color.json b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/element/string.json b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..21ab31f05b93d822857d50d85e56dcb91d84007d --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "call_V_RSA" + } + ] +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/media/icon.png b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/media/icon.png differ diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/profile/main_pages.json b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/resources/en_US/element/string.json b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..21ab31f05b93d822857d50d85e56dcb91d84007d --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "call_V_RSA" + } + ] +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/main/resources/zh_CN/element/string.json b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..d70783cc0bd7dfd2463278311593956ad6c0f344 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "模块描述" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "call_V_RSA" + } + ] +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..4ca645e6013cfce8e7dbb728313cb8840c4da660 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import hilog from '@ohos.hilog'; +import { Hypium } from '@ohos/hypium'; +import testsuite from '../test/List.test'; +import window from '@ohos.window'; + +export default class TestAbility extends UIAbility { + onCreate(want, launchParam) { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate'); + hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? ''); + hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:'+ JSON.stringify(launchParam) ?? ''); + var abilityDelegator: any + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var abilityDelegatorArguments: any + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!'); + Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) + } + + onDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage) { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageCreate'); + windowStage.loadContent('testability/pages/Index', (err, data) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', + JSON.stringify(data) ?? ''); + }); + } + + onWindowStageDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageDestroy'); + } + + onForeground() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onForeground'); + } + + onBackground() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onBackground'); + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..cef0447cd2f137ef82d223ead2e156808878ab90 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import hilog from '@ohos.hilog'; + +@Entry +@Component +struct Index { + aboutToAppear() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility index aboutToAppear'); + } + @State message: string = 'Hello World' + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('next page') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .width('35%') + .height('5%') + .onClick(()=>{ + }) + } + .width('100%') + } + .height('100%') + } + } \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..1def08f2e9dcbfa3454a07b7a3b82b173bb90d02 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import hilog from '@ohos.hilog'; +import TestRunner from '@ohos.application.testRunner'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +var abilityDelegator = undefined +var abilityDelegatorArguments = undefined + +async function onAbilityCreateCallback() { + hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback'); +} + +async function addAbilityMonitorCallback(err: any) { + hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? ''); +} + +export default class OpenHarmonyTestRunner implements TestRunner { + constructor() { + } + + onPrepare() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare '); + } + + async onRun() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run'); + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility' + let lMonitor = { + abilityName: testAbilityName, + onAbilityCreate: onAbilityCreateCallback, + }; + abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback) + var cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName + var debug = abilityDelegatorArguments.parameters['-D'] + if (debug == 'true') + { + cmd += ' -D' + } + hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd); + abilityDelegator.executeShellCommand(cmd, + (err: any, d: any) => { + hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? ''); + }) + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end'); + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/module.json5 b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..fab77ce2e0c61e3ad010bab5b27ccbd15f9a8c96 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/module.json5 @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "module": { + "name": "entry_test", + "type": "feature", + "description": "$string:module_test_desc", + "mainElement": "TestAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:test_pages", + "abilities": [ + { + "name": "TestAbility", + "srcEntry": "./ets/testability/TestAbility.ets", + "description": "$string:TestAbility_desc", + "icon": "$media:icon", + "label": "$string:TestAbility_label", + "exported": true, + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ] + } + ] + } +} diff --git a/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/element/color.json b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/element/string.json b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..65d8fa5a7cf54aa3943dcd0214f58d1771bc1f6c --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_test_desc", + "value": "test ability description" + }, + { + "name": "TestAbility_desc", + "value": "the test ability" + }, + { + "name": "TestAbility_label", + "value": "test label" + } + ] +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/media/icon.png b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/media/icon.png differ diff --git a/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..b7e7343cacb32ce982a45e76daad86e435e054fe --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "testability/pages/Index" + ] +} diff --git a/flutter_rsa_ohos/example/ohos/hvigor/hvigor-config.json5 b/flutter_rsa_ohos/example/ohos/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..3bcb859e88b72cc2dcc6ec1bc89d26a6411cb2d8 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/hvigor/hvigor-config.json5 @@ -0,0 +1,23 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "modelVersion": "5.0.0", + "dependencies": { + }, + "properties": { + "ohos.nativeResolver": false + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/hvigorfile.ts b/flutter_rsa_ohos/example/ohos/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f2d2aafe6d6a3a71a9944ebd0c91fbc308ac9d1 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/hvigorfile.ts @@ -0,0 +1,21 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/ohos/oh-package.json5 b/flutter_rsa_ohos/example/ohos/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..46d4bc52566bb9141a158f8363202a8f9c848dc8 --- /dev/null +++ b/flutter_rsa_ohos/example/ohos/oh-package.json5 @@ -0,0 +1,21 @@ +{ + "modelVersion": "5.0.0", + "name": "flutter_rsa_ohos_example", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + "@ohos/flutter_ohos": "file:./har/flutter.har" + }, + "devDependencies": { + "@ohos/hypium": "1.0.6" + }, + "overrides": { + "flutter_rsa_ohos": "file:./har/flutter_rsa_ohos.har", + "integration_test": "file:./har/integration_test.har", + "@ohos/flutter_module": "file:./entry", + "@ohos/flutter_ohos": "file:./har/flutter.har" + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/example/pubspec.yaml b/flutter_rsa_ohos/example/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dcdf7b6e68fd684ad3e1ac77b992195de37f397b --- /dev/null +++ b/flutter_rsa_ohos/example/pubspec.yaml @@ -0,0 +1,103 @@ +name: flutter_rsa_ohos_example +description: Demonstrates how to use the flutter_rsa_ohos plugin. +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +environment: + sdk: '>=2.19.6 <3.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + flutter_rsa_ohos: + # When depending on this package from a real application you should use: + # flutter_rsa_ohos: ^x.y.z + # See https://dart.dev/tools/pub/dependencies#version-constraints + # The example app is bundled with the plugin so we use a path dependency on + # the parent directory to use the current plugin's version. + path: ../ + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + integration_test: + sdk: flutter + test: any + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # See https://github.com/flutter/flutter/wiki/Desktop-shells#fonts + fonts: + - family: Roboto + fonts: + - asset: fonts/Roboto/Roboto-Thin.ttf + weight: 100 + - asset: fonts/Roboto/Roboto-Light.ttf + weight: 300 + - asset: fonts/Roboto/Roboto-Regular.ttf + weight: 400 + - asset: fonts/Roboto/Roboto-Medium.ttf + weight: 500 + - asset: fonts/Roboto/Roboto-Bold.ttf + weight: 700 + - asset: fonts/Roboto/Roboto-Black.ttf + weight: 900 + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/flutter_rsa_ohos/lib/bridge/binding.dart b/flutter_rsa_ohos/lib/bridge/binding.dart new file mode 100644 index 0000000000000000000000000000000000000000..ac9cb9c5669d62da3584e7e3953a31cc319e693f --- /dev/null +++ b/flutter_rsa_ohos/lib/bridge/binding.dart @@ -0,0 +1,220 @@ +import 'dart:async'; +import 'dart:ffi' as ffi; +import 'dart:io'; +import 'dart:isolate'; + +import 'package:flutter_rsa_ohos/fast_rsa_ohos.dart'; +import 'package:ffi/ffi.dart'; +import 'package:flutter_rsa_ohos/bridge/ffi.dart'; +import 'package:flutter_rsa_ohos/bridge/isolate.dart'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as Path; + +class Binding { + static final String _callFuncName = 'RSABridgeCall'; + static final String _libraryName = 'librsa_bridge'; + static final Binding _singleton = Binding._internal(); + + late ffi.DynamicLibrary _library; + + factory Binding() { + return _singleton; + } + + Binding._internal() { + _library = openLib(); + } + + static void callBridge(IsolateArguments args) async { + var result = await Binding().call(args.name, args.payload); + args.port.send(result); + } + + Future callAsync(String name, Uint8List payload) async { + final port = ReceivePort('${_libraryName}_port'); + final args = IsolateArguments(name, payload, port.sendPort); + final completer = new Completer(); + + final isolate = await Isolate.spawn( + callBridge, + args, + errorsAreFatal: false, + debugName: '${_libraryName}_isolate', + onError: port.sendPort, + ); + + port.listen( + (message) async { + if (message is Uint8List) { + completer.complete(message); + } else if (message is List) { + completer.completeError(message.isEmpty); + } else { + completer.completeError(message ?? "spawn error"); + } + port.close(); + }, + onDone: () { + isolate.kill(priority: Isolate.beforeNextEvent); + }, + ); + + return completer.future; + } + + Future call(String name, Uint8List payload) async { + final callable = _library + .lookup>(_callFuncName) + .asFunction(); + + final pointer = malloc(payload.length); + + // https://github.com/dart-lang/ffi/issues/27 + // https://github.com/objectbox/objectbox-dart/issues/69 + for (var i = 0; i < payload.length; i++) { + pointer[i] = payload[i]; + } + final payloadPointer = pointer.cast(); + final namePointer = toUtf8(name); + + final result = callable(namePointer, payloadPointer, payload.length); + + malloc.free(namePointer); + malloc.free(pointer); + + handleError(result.ref.error, result); + + final output = + result.ref.message.cast().asTypedList(result.ref.size); + freeResult(result); + return output; + } + + void handleError( + ffi.Pointer error, ffi.Pointer result) { + if (error.address != ffi.nullptr.address) { + var message = fromUtf8(error); + freeResult(result); + throw new RSAException(message); + } + } + + ffi.Pointer toUtf8(String? text) { + return text == null ? "".toNativeUtf8() : text.toNativeUtf8(); + } + + String fromUtf8(ffi.Pointer? text) { + return text == null ? "" : text.toDartString(); + } + + void freeResult(ffi.Pointer result) { + if (!Platform.isWindows) { + malloc.free(result); + } + } + + bool isSupported() { + return Platform.isWindows || + Platform.isLinux || + Platform.isAndroid || + Platform.isMacOS || + Platform.isFuchsia || + Platform.isIOS; + } + + void validateTestFFIFile(String path) { + if (!File(path).existsSync()) { + debugPrint('dynamic library not found: $path'); + throw Exception( + '''In order to be able to run unit tests, you need to run the project first: "flutter run -d ${Platform.operatingSystem}"'''); + } + } + + Directory _findAppDirectory(Directory directory) { + try { + return directory + .listSync(recursive: false, followLinks: false) + .whereType() + .firstWhere((dir) => dir.path.endsWith('.app')); + } catch (e) { + return directory; + } + } + + ffi.DynamicLibrary openLib() { + var isFlutterTest = Platform.environment.containsKey('FLUTTER_TEST'); + + if (Platform.isMacOS || Platform.isIOS) { + if (isFlutterTest) { + final appDirectory = + _findAppDirectory(Directory('build/macos/Build/Products/Debug')); + var ffiFile = Path.join( + appDirectory.path, "Contents", "Frameworks", "$_libraryName.dylib"); + validateTestFFIFile(ffiFile); + return ffi.DynamicLibrary.open(ffiFile); + } + if (Platform.isMacOS) { + return ffi.DynamicLibrary.open("$_libraryName.dylib"); + } + if (Platform.isIOS) { + return ffi.DynamicLibrary.process(); + } + } + + if (Platform.isAndroid || Platform.isLinux) { + if (isFlutterTest) { + var arch = + Platform.resolvedExecutable.contains("linux-x64") ? "x64" : "arm64"; + + var ffiFile = 'build/linux/$arch/debug/bundle/lib/$_libraryName.so'; + validateTestFFIFile(ffiFile); + print("fast_rsa:: openLib ffi.DynamicLibrary.open"); + return ffi.DynamicLibrary.open(ffiFile); + } + + if (Platform.isLinux) { + try { + return ffi.DynamicLibrary.open("$_libraryName.so"); + } catch (e) { + print(e); + var binary = File("/proc/self/cmdline").readAsStringSync(); + var suggestedFile = + Path.join(Path.dirname(binary), "lib", "$_libraryName.so"); + return ffi.DynamicLibrary.open(suggestedFile); + } + } + + if (Platform.isAndroid) { + try { + return ffi.DynamicLibrary.open("$_libraryName.so"); + } catch (e) { + print("fast_rsa:: fallback to open DynamicLibrary on older devices"); + //fallback for devices that cannot load dynamic libraries by name: load the library with an absolute path + //read the app id + var appid = File("/proc/self/cmdline").readAsStringSync(); + // the file /proc/self/cmdline returns a string with many trailing \0 characters, which makes the string pretty useless for dart, many + // operations will not work correctly. remove these trailing zero bytes. + appid = String.fromCharCodes( + appid.codeUnits.where((element) => element != 0)); + final loadPath = "/data/data/$appid/lib/$_libraryName.so"; + return ffi.DynamicLibrary.open(loadPath); + } + } + } + + if (Platform.isWindows) { + if (isFlutterTest) { + var arch = + Platform.resolvedExecutable.contains("x64") ? "x64" : "arm64"; + + var ffiFile = Path.canonicalize(Path.join( + r'build\windows', arch, r'runner\Debug', '$_libraryName.dll')); + validateTestFFIFile(ffiFile); + return ffi.DynamicLibrary.open(ffiFile); + } + return ffi.DynamicLibrary.open("$_libraryName.dll"); + } + + throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}'); + } +} diff --git a/flutter_rsa_ohos/lib/bridge/binding_stub.dart b/flutter_rsa_ohos/lib/bridge/binding_stub.dart new file mode 100644 index 0000000000000000000000000000000000000000..e911a120f84ccfd76c6a1278fd0e367f0188bce7 --- /dev/null +++ b/flutter_rsa_ohos/lib/bridge/binding_stub.dart @@ -0,0 +1,20 @@ +import 'dart:async'; +import 'dart:typed_data'; + +class Binding { + static final Binding _singleton = Binding._internal(); + + factory Binding() { + return _singleton; + } + + Binding._internal(); + + Future callAsync(String name, Uint8List payload) async { + return Uint8List.fromList(''.codeUnits); + } + + bool isSupported() { + return false; + } +} diff --git a/flutter_rsa_ohos/lib/bridge/ffi.dart b/flutter_rsa_ohos/lib/bridge/ffi.dart new file mode 100644 index 0000000000000000000000000000000000000000..101165c296e177a5d650fcfea74f9b756cc47e4d --- /dev/null +++ b/flutter_rsa_ohos/lib/bridge/ffi.dart @@ -0,0 +1,22 @@ +import 'dart:ffi' as ffi; +import 'package:ffi/ffi.dart'; + +typedef call_func = ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ffi.Int32, +); +typedef Call = ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + int, +); + +class FFIBytesReturn extends ffi.Struct { + external ffi.Pointer message; + + @ffi.Int32() + external int size; + + external ffi.Pointer error; +} diff --git a/flutter_rsa_ohos/lib/bridge/isolate.dart b/flutter_rsa_ohos/lib/bridge/isolate.dart new file mode 100644 index 0000000000000000000000000000000000000000..cd224759b70585a2da0e900cfb9b539bc0708d7b --- /dev/null +++ b/flutter_rsa_ohos/lib/bridge/isolate.dart @@ -0,0 +1,10 @@ +import 'dart:isolate'; +import 'dart:typed_data'; + +class IsolateArguments { + final String name; + final Uint8List payload; + final SendPort port; + + IsolateArguments(this.name, this.payload, this.port); +} diff --git a/flutter_rsa_ohos/lib/fast_rsa_ohos.dart b/flutter_rsa_ohos/lib/fast_rsa_ohos.dart new file mode 100644 index 0000000000000000000000000000000000000000..8574ec5a03072618e7606d1df599c8f00a347cb9 --- /dev/null +++ b/flutter_rsa_ohos/lib/fast_rsa_ohos.dart @@ -0,0 +1,766 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/services.dart'; +import 'package:flutter_rsa_ohos/bridge/binding_stub.dart' +if (dart.library.io) 'package:flutter_rsa_ohos/bridge/binding.dart' +if (dart.library.js) 'package:flutter_rsa_ohos/bridge/binding_stub.dart'; +import 'package:flutter_rsa_ohos/model/bridge_model_generated.dart' as model; + +class RSAException implements Exception { + String cause; + + RSAException(this.cause); + + @override + String toString() { + return 'RSAException: $cause'; + } +} + +enum Hash { MD5, SHA1, SHA224, SHA256, SHA384, SHA512 } + +enum PEMCipher { DES, D3DES, AES128, AES192, AES256 } + +enum SaltLength { AUTO, EQUALS_HASH } + +class KeyPair { + String publicKey; + String privateKey; + + KeyPair(this.publicKey, this.privateKey); +} + +class PKCS12KeyPair { + String publicKey; + String privateKey; + String certificate; + + PKCS12KeyPair(this.publicKey, this.privateKey, this.certificate); +} + +class RSA { + static const MethodChannel _channel = MethodChannel('fast_rsa'); + static bool bindingEnabled = Platform.operatingSystem == "ohos" ? false : Binding().isSupported(); + + static Future _call(String name, Uint8List payload) async { + if (bindingEnabled) { + return await Binding().callAsync(name, payload); + } + return await _channel.invokeMethod(name, { + "payload": payload, + }); + } + + static Future _bytesResponse( + String name, Uint8List payload) async { + var data = await _call(name, payload); + var response = model.BytesResponse(data); + if (response.error != null && response.error != "") { + throw RSAException(response.error!); + } + return Uint8List.fromList(response.output!); + } + + static Future _stringResponse(String name, Uint8List payload) async { + var data = await _call(name, payload); + var response = model.StringResponse(data); + if (response.error != null && response.error != "") { + throw RSAException(response.error!); + } + return response.output!; + } + + static String _toHex(List bytes) { + return bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' '); + } + + static Future _boolResponse(String name, Uint8List payload) async { + var data = await _call(name, payload); + var response = model.BoolResponse(data); + if (response.error != null && response.error != "") { + throw RSAException(response.error!); + } + return response.output; + } + + static Future _keyPairResponse( + String name, Uint8List payload) async { + var data = await _call(name, payload); + var response = model.KeyPairResponse(data); + if (response.error != null && response.error != "") { + throw RSAException(response.error!); + } + var output = response.output!; + return KeyPair(output.publicKey!, output.privateKey!); + } + + static Future _pkcs12KeyPairResponse( + String name, Uint8List payload) async { + var data = await _call(name, payload); + var response = model.PKCS12KeyPairResponse(data); + if (response.error != null && response.error != "") { + throw RSAException(response.error!); + } + var output = response.output!; + return PKCS12KeyPair( + output.publicKey!, output.privateKey!, output.certificate!); + } + + static Future convertJWKToPrivateKey( + dynamic data, String keyId) async { + var requestBuilder = model.ConvertJWTRequestObjectBuilder( + data: jsonEncode(data), + keyId: keyId, + ); + if(Platform.operatingSystem == 'ohos') { + throw RSAException('HarmonyOS not support convertJWKToPrivateKey.'); + } + return await _stringResponse( + "convertJWKToPrivateKey", requestBuilder.toBytes()); + } + + static Future convertJWKToPublicKey( + dynamic data, String keyId) async { + var requestBuilder = model.ConvertJWTRequestObjectBuilder( + data: jsonEncode(data), + keyId: keyId, + ); + if(Platform.operatingSystem == 'ohos') { + throw RSAException('HarmonyOS not support convertJWKToPublicKey.'); + } + + return await _stringResponse( + "convertJWKToPublicKey", requestBuilder.toBytes()); + } + + static Future convertKeyPairToPKCS12( + String privateKey, String certificate, String password) async { + var requestBuilder = model.ConvertKeyPairRequestObjectBuilder( + certificate: certificate, + password: password, + privateKey: privateKey, + ); + if(Platform.operatingSystem == 'ohos') { + throw RSAException('HarmonyOS not support convertKeyPairToPKCS12.'); + } + + return await _stringResponse( + "convertKeyPairToPKCS12", requestBuilder.toBytes()); + } + + static Future convertPKCS12ToKeyPair( + String pkcs12, String password) async { + var requestBuilder = model.ConvertPKCS12RequestObjectBuilder( + password: password, + pkcs12: pkcs12, + ); + if(Platform.operatingSystem == 'ohos') { + throw RSAException('HarmonyOS not support convertPKCS12ToKeyPair.'); + } + + return await _pkcs12KeyPairResponse( + "convertPKCS12ToKeyPair", requestBuilder.toBytes()); + } + + static Future convertPrivateKeyToPKCS8(String privateKey) async { + var requestBuilder = model.ConvertPrivateKeyRequestObjectBuilder( + privateKey: privateKey, + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("convertPrivateKeyToPKCS8", { + 'privateKey': privateKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse( + "convertPrivateKeyToPKCS8", requestBuilder.toBytes()); + } + + static Future convertPrivateKeyToPKCS1(String privateKey) async { + var requestBuilder = model.ConvertPrivateKeyRequestObjectBuilder( + privateKey: privateKey, + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("convertPrivateKeyToPKCS1", { + 'privateKey': privateKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse( + "convertPrivateKeyToPKCS1", requestBuilder.toBytes()); + } + + static Future convertPrivateKeyToJWK(String privateKey) async { + var requestBuilder = model.ConvertPrivateKeyRequestObjectBuilder( + privateKey: privateKey, + ); + if(Platform.operatingSystem == 'ohos') { + throw RSAException('HarmonyOS not support convertPrivateKeyToJWK.'); + } + + return jsonDecode(await _stringResponse( + "convertPrivateKeyToJWK", requestBuilder.toBytes())); + } + + static Future convertPrivateKeyToPublicKey(String privateKey) async { + var requestBuilder = model.ConvertPrivateKeyRequestObjectBuilder( + privateKey: privateKey, + ); + if(Platform.operatingSystem == 'ohos') { + throw RSAException('HarmonyOS not support convertPrivateKeyToPublicKey.'); + } + + return await _stringResponse( + "convertPrivateKeyToPublicKey", requestBuilder.toBytes()); + } + + static Future convertPublicKeyToPKIX(String publicKey) async { + var requestBuilder = model.ConvertPublicKeyRequestObjectBuilder( + publicKey: publicKey, + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("convertPublicKeyToPKIX", { + 'publicKey': publicKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse( + "convertPublicKeyToPKIX", requestBuilder.toBytes()); + } + + static Future convertPublicKeyToPKCS1(String publicKey) async { + var requestBuilder = model.ConvertPublicKeyRequestObjectBuilder( + publicKey: publicKey, + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("convertPublicKeyToPKCS1", { + 'publicKey': publicKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse( + "convertPublicKeyToPKCS1", requestBuilder.toBytes()); + } + + static Future convertPublicKeyToJWK(String publicKey) async { + var requestBuilder = model.ConvertPublicKeyRequestObjectBuilder( + publicKey: publicKey, + ); + if(Platform.operatingSystem == 'ohos') { + throw RSAException('HarmonyOS not support convertPublicKeyToJWK.'); + } + + return jsonDecode(await _stringResponse( + "convertPublicKeyToJWK", requestBuilder.toBytes())); + } + + static Future decryptPrivateKey( + String privateKeyEncrypted, String password) async { + var requestBuilder = model.DecryptPrivateKeyRequestObjectBuilder( + privateKeyEncrypted: privateKeyEncrypted, + password: password, + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("decryptPrivateKey", { + 'privateKeyEncrypted': privateKeyEncrypted, + 'password': password, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("decryptPrivateKey", requestBuilder.toBytes()); + } + + static Future encryptPrivateKey( + String privateKey, String password, PEMCipher cipher) async { + var requestBuilder = model.EncryptPrivateKeyRequestObjectBuilder( + privateKey: privateKey, + password: password, + cipher: model.PEMCipher.values[cipher.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("encryptPrivateKey", { + 'privateKey': privateKey, + 'password': password, + 'cipher': cipher.toString(), + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("encryptPrivateKey", requestBuilder.toBytes()); + } + + static Future decryptOAEP( + String ciphertext, String label, Hash hash, String privateKey) async { + var requestBuilder = model.DecryptOAEPRequestObjectBuilder( + privateKey: privateKey, + ciphertext: ciphertext, + label: label, + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("decryptOAEP", { + 'ciphertext': ciphertext, + 'hash': hash.toString(), + 'label': label, + 'privateKey': privateKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("decryptOAEP", requestBuilder.toBytes()); + } + + static Future decryptOAEPBytes( + Uint8List ciphertext, String label, Hash hash, String privateKey) async { + var requestBuilder = model.DecryptOAEPBytesRequestObjectBuilder( + privateKey: privateKey, + ciphertext: ciphertext, + label: label, + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("decryptOAEPBytes", { + 'ciphertext': ciphertext, + 'hash': hash.toString(), + 'label': label, + 'privateKey': privateKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _bytesResponse("decryptOAEPBytes", requestBuilder.toBytes()); + } + + static Future decryptPKCS1v15( + String ciphertext, String privateKey) async { + var requestBuilder = model.DecryptPKCS1v15RequestObjectBuilder( + privateKey: privateKey, + ciphertext: ciphertext, + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("decryptPKCS1v15", { + 'ciphertext': ciphertext, + 'privateKey': privateKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("decryptPKCS1v15", requestBuilder.toBytes()); + } + + static Future decryptPKCS1v15Bytes( + Uint8List ciphertext, String privateKey) async { + var requestBuilder = model.DecryptPKCS1v15BytesRequestObjectBuilder( + privateKey: privateKey, + ciphertext: ciphertext, + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("decryptPKCS1v15Bytes", { + 'ciphertext': ciphertext, + 'privateKey': privateKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _bytesResponse( + "decryptPKCS1v15Bytes", requestBuilder.toBytes()); + } + + static Future encryptOAEP( + String message, String label, Hash hash, String publicKey) async { + var requestBuilder = model.EncryptOAEPRequestObjectBuilder( + message: message, + label: label, + publicKey: publicKey, + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("encryptOAEP", { + 'message': message, + 'hash': hash.toString(), + 'label': label, + 'publicKey': publicKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + return await _stringResponse("encryptOAEP", requestBuilder.toBytes()); + } + + static Future encryptOAEPBytes( + Uint8List message, String label, Hash hash, String publicKey) async { + var requestBuilder = model.EncryptOAEPBytesRequestObjectBuilder( + message: message, + label: label, + publicKey: publicKey, + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("encryptOAEPBytes", { + 'message': message, + 'hash': hash.toString(), + 'label': label, + 'publicKey': publicKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _bytesResponse("encryptOAEPBytes", requestBuilder.toBytes()); + } + + static Future encryptPKCS1v15( + String message, String publicKey) async { + var requestBuilder = model.EncryptPKCS1v15RequestObjectBuilder( + message: message, + publicKey: publicKey, + ); + if(Platform.operatingSystem == 'ohos') { + try{ + var data = await _channel.invokeMethod("encryptPKCS1v15", { + 'message': message, + 'publicKey': publicKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("encryptPKCS1v15", requestBuilder.toBytes()); + } + + static Future encryptPKCS1v15Bytes( + Uint8List message, String publicKey) async { + var requestBuilder = model.EncryptPKCS1v15BytesRequestObjectBuilder( + message: message, + publicKey: publicKey, + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("encryptPKCS1v15Bytes", { + 'message': message, + 'publicKey': publicKey, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _bytesResponse( + "encryptPKCS1v15Bytes", requestBuilder.toBytes()); + } + + static Future signPSS(String message, Hash hash, + SaltLength saltLength, String privateKey) async { + var requestBuilder = model.SignPSSRequestObjectBuilder( + message: message, + privateKey: privateKey, + saltLength: model.SaltLength.values[saltLength.index], + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("signPSS", { + 'message': message, + 'privateKey': privateKey, + 'saltLength': saltLength.toString(), + 'hash': hash.toString(), + }); + return await data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("signPSS", requestBuilder.toBytes()); + } + + static Future signPSSBytes(Uint8List message, Hash hash, + SaltLength saltLength, String privateKey) async { + var requestBuilder = model.SignPSSBytesRequestObjectBuilder( + message: message, + privateKey: privateKey, + saltLength: model.SaltLength.values[saltLength.index], + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("signPSSBytes", { + 'message': message, + 'privateKey': privateKey, + 'saltLength': saltLength.toString(), + 'hash': hash.toString(), + }); + return await data; + } catch (e) { + throw RSAException(e.toString()); + } + } + return await _bytesResponse("signPSSBytes", requestBuilder.toBytes()); + } + + static Future signPKCS1v15( + String message, Hash hash, String privateKey) async { + var requestBuilder = model.SignPKCS1v15RequestObjectBuilder( + message: message, + privateKey: privateKey, + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("signPKCS1v15", { + 'message': message, + 'privateKey': privateKey, + 'hash': hash.toString(), + }); + return await data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("signPKCS1v15", requestBuilder.toBytes()); + } + + static Future signPKCS1v15Bytes( + Uint8List message, Hash hash, String privateKey) async { + var requestBuilder = model.SignPKCS1v15BytesRequestObjectBuilder( + message: message, + privateKey: privateKey, + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("signPKCS1v15Bytes", { + 'message': message, + 'privateKey': privateKey, + 'hash': hash.toString(), + }); + return await data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _bytesResponse("signPKCS1v15Bytes", requestBuilder.toBytes()); + } + + static Future verifyPSS(String signature, String message, Hash hash, + SaltLength saltLength, String publicKey) async { + var requestBuilder = model.VerifyPSSRequestObjectBuilder( + message: message, + signature: signature, + publicKey: publicKey, + saltLength: model.SaltLength.values[saltLength.index], + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("verifyPSS", { + 'message': message, + 'signature': signature, + 'publicKey': publicKey, + 'saltLength': saltLength.toString(), + 'hash': hash.toString(), + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _boolResponse("verifyPSS", requestBuilder.toBytes()); + } + + static Future verifyPSSBytes(Uint8List signature, Uint8List message, + Hash hash, SaltLength saltLength, String publicKey) async { + var requestBuilder = model.VerifyPSSBytesRequestObjectBuilder( + message: message, + signature: signature, + publicKey: publicKey, + saltLength: model.SaltLength.values[saltLength.index], + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("verifyPSSBytes", { + 'message': message, + 'signature': signature, + 'publicKey': publicKey, + 'saltLength': saltLength.toString(), + 'hash': hash.toString(), + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _boolResponse("verifyPSSBytes", requestBuilder.toBytes()); + } + + static Future verifyPKCS1v15( + String signature, String message, Hash hash, String publicKey) async { + var requestBuilder = model.VerifyPKCS1v15RequestObjectBuilder( + message: message, + signature: signature, + publicKey: publicKey, + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("verifyPKCS1v15", { + 'message': message, + 'signature': signature, + 'publicKey': publicKey, + 'hash': hash.toString(), + }); + return await data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _boolResponse("verifyPKCS1v15", requestBuilder.toBytes()); + } + + static Future verifyPKCS1v15Bytes(Uint8List signature, + Uint8List message, Hash hash, String publicKey) async { + var requestBuilder = model.VerifyPKCS1v15BytesRequestObjectBuilder( + message: message, + signature: signature, + publicKey: publicKey, + hash: model.Hash.values[hash.index], + ); + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("verifyPKCS1v15Bytes", { + 'message': message, + 'signature': signature, + 'publicKey': publicKey, + 'hash': hash.toString(), + }); + return await data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _boolResponse("verifyPKCS1v15Bytes", requestBuilder.toBytes()); + } + + static Future hash(String message, Hash hash) async { + var requestBuilder = model.HashRequestObjectBuilder( + message: message, + hash: model.Hash.values[hash.index], + ); + + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("hash", { + 'message': message, + 'hash': hash.toString(), + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("hash", requestBuilder.toBytes()); + } + + static Future base64(String message) async { + var requestBuilder = model.Base64RequestObjectBuilder( + message: message, + ); + + if(Platform.operatingSystem == 'ohos') { + try { + var data = await _channel.invokeMethod("base64", { + 'message': message, + }); + return data; + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _stringResponse("base64", requestBuilder.toBytes()); + } + + static Future generate(int bits) async { + var requestBuilder = model.GenerateRequestObjectBuilder( + nBits: bits, + ); + if(Platform.operatingSystem == 'ohos') { + try { + final result = await _channel.invokeMethod("generate", { + 'nBits': bits, + }); + final publicKey = result['publicKey'] as String; + final privateKey = result['privateKey'] as String; + return KeyPair(publicKey, privateKey); + } catch (e) { + throw RSAException(e.toString()); + } + } + + return await _keyPairResponse("generate", requestBuilder.toBytes()); + } +} diff --git a/flutter_rsa_ohos/lib/model/bridge_model_generated.dart b/flutter_rsa_ohos/lib/model/bridge_model_generated.dart new file mode 100644 index 0000000000000000000000000000000000000000..9f54552aed9e97749684be3fd7aa214c4759b2d2 --- /dev/null +++ b/flutter_rsa_ohos/lib/model/bridge_model_generated.dart @@ -0,0 +1,3830 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable + +library model; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +class SaltLength { + final int value; + const SaltLength._(this.value); + + factory SaltLength.fromValue(int value) { + final result = values[value]; + if (result == null) { + throw StateError('Invalid value $value for bit flag enum SaltLength'); + } + return result; + } + + static SaltLength? _createOrNull(int? value) => + value == null ? null : SaltLength.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 1; + static bool containsValue(int value) => values.containsKey(value); + + static const SaltLength AUTO = SaltLength._(0); + static const SaltLength EQUALS_HASH = SaltLength._(1); + static const Map values = {0: AUTO, 1: EQUALS_HASH}; + + static const fb.Reader reader = _SaltLengthReader(); + + @override + String toString() { + return 'SaltLength{value: $value}'; + } +} + +class _SaltLengthReader extends fb.Reader { + const _SaltLengthReader(); + + @override + int get size => 1; + + @override + SaltLength read(fb.BufferContext bc, int offset) => + SaltLength.fromValue(const fb.Int32Reader().read(bc, offset)); +} + +class PEMCipher { + final int value; + const PEMCipher._(this.value); + + factory PEMCipher.fromValue(int value) { + final result = values[value]; + if (result == null) { + throw StateError('Invalid value $value for bit flag enum PEMCipher'); + } + return result; + } + + static PEMCipher? _createOrNull(int? value) => + value == null ? null : PEMCipher.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 4; + static bool containsValue(int value) => values.containsKey(value); + + static const PEMCipher DES = PEMCipher._(0); + static const PEMCipher D3DES = PEMCipher._(1); + static const PEMCipher AES128 = PEMCipher._(2); + static const PEMCipher AES192 = PEMCipher._(3); + static const PEMCipher AES256 = PEMCipher._(4); + static const Map values = { + 0: DES, + 1: D3DES, + 2: AES128, + 3: AES192, + 4: AES256 + }; + + static const fb.Reader reader = _PEMCipherReader(); + + @override + String toString() { + return 'PEMCipher{value: $value}'; + } +} + +class _PEMCipherReader extends fb.Reader { + const _PEMCipherReader(); + + @override + int get size => 1; + + @override + PEMCipher read(fb.BufferContext bc, int offset) => + PEMCipher.fromValue(const fb.Int32Reader().read(bc, offset)); +} + +class Hash { + final int value; + const Hash._(this.value); + + factory Hash.fromValue(int value) { + final result = values[value]; + if (result == null) { + throw StateError('Invalid value $value for bit flag enum Hash'); + } + return result; + } + + static Hash? _createOrNull(int? value) => + value == null ? null : Hash.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 5; + static bool containsValue(int value) => values.containsKey(value); + + static const Hash MD5 = Hash._(0); + static const Hash SHA1 = Hash._(1); + static const Hash SHA224 = Hash._(2); + static const Hash SHA256 = Hash._(3); + static const Hash SHA384 = Hash._(4); + static const Hash SHA512 = Hash._(5); + static const Map values = { + 0: MD5, + 1: SHA1, + 2: SHA224, + 3: SHA256, + 4: SHA384, + 5: SHA512 + }; + + static const fb.Reader reader = _HashReader(); + + @override + String toString() { + return 'Hash{value: $value}'; + } +} + +class _HashReader extends fb.Reader { + const _HashReader(); + + @override + int get size => 1; + + @override + Hash read(fb.BufferContext bc, int offset) => + Hash.fromValue(const fb.Int32Reader().read(bc, offset)); +} + +class ConvertJWTRequest { + ConvertJWTRequest._(this._bc, this._bcOffset); + factory ConvertJWTRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _ConvertJWTRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get data => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get keyId => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'ConvertJWTRequest{data: $data, keyId: $keyId}'; + } +} + +class _ConvertJWTRequestReader extends fb.TableReader { + const _ConvertJWTRequestReader(); + + @override + ConvertJWTRequest createObject(fb.BufferContext bc, int offset) => + ConvertJWTRequest._(bc, offset); +} + +class ConvertJWTRequestBuilder { + ConvertJWTRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addDataOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addKeyIdOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class ConvertJWTRequestObjectBuilder extends fb.ObjectBuilder { + final String? _data; + final String? _keyId; + + ConvertJWTRequestObjectBuilder({ + String? data, + String? keyId, + }) : _data = data, + _keyId = keyId; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? dataOffset = + _data == null ? null : fbBuilder.writeString(_data!); + final int? keyIdOffset = + _keyId == null ? null : fbBuilder.writeString(_keyId!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, dataOffset); + fbBuilder.addOffset(1, keyIdOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class ConvertKeyPairRequest { + ConvertKeyPairRequest._(this._bc, this._bcOffset); + factory ConvertKeyPairRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _ConvertKeyPairRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get certificate => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + String? get password => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 8); + + @override + String toString() { + return 'ConvertKeyPairRequest{privateKey: $privateKey, certificate: $certificate, password: $password}'; + } +} + +class _ConvertKeyPairRequestReader + extends fb.TableReader { + const _ConvertKeyPairRequestReader(); + + @override + ConvertKeyPairRequest createObject(fb.BufferContext bc, int offset) => + ConvertKeyPairRequest._(bc, offset); +} + +class ConvertKeyPairRequestBuilder { + ConvertKeyPairRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addCertificateOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addPasswordOffset(int? offset) { + fbBuilder.addOffset(2, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class ConvertKeyPairRequestObjectBuilder extends fb.ObjectBuilder { + final String? _privateKey; + final String? _certificate; + final String? _password; + + ConvertKeyPairRequestObjectBuilder({ + String? privateKey, + String? certificate, + String? password, + }) : _privateKey = privateKey, + _certificate = certificate, + _password = password; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + final int? certificateOffset = + _certificate == null ? null : fbBuilder.writeString(_certificate!); + final int? passwordOffset = + _password == null ? null : fbBuilder.writeString(_password!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, privateKeyOffset); + fbBuilder.addOffset(1, certificateOffset); + fbBuilder.addOffset(2, passwordOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class ConvertPKCS12Request { + ConvertPKCS12Request._(this._bc, this._bcOffset); + factory ConvertPKCS12Request(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _ConvertPKCS12RequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get pkcs12 => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get password => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'ConvertPKCS12Request{pkcs12: $pkcs12, password: $password}'; + } +} + +class _ConvertPKCS12RequestReader extends fb.TableReader { + const _ConvertPKCS12RequestReader(); + + @override + ConvertPKCS12Request createObject(fb.BufferContext bc, int offset) => + ConvertPKCS12Request._(bc, offset); +} + +class ConvertPKCS12RequestBuilder { + ConvertPKCS12RequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addPkcs12Offset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPasswordOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class ConvertPKCS12RequestObjectBuilder extends fb.ObjectBuilder { + final String? _pkcs12; + final String? _password; + + ConvertPKCS12RequestObjectBuilder({ + String? pkcs12, + String? password, + }) : _pkcs12 = pkcs12, + _password = password; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? pkcs12Offset = + _pkcs12 == null ? null : fbBuilder.writeString(_pkcs12!); + final int? passwordOffset = + _password == null ? null : fbBuilder.writeString(_password!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, pkcs12Offset); + fbBuilder.addOffset(1, passwordOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class ConvertPrivateKeyRequest { + ConvertPrivateKeyRequest._(this._bc, this._bcOffset); + factory ConvertPrivateKeyRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _ConvertPrivateKeyRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'ConvertPrivateKeyRequest{privateKey: $privateKey}'; + } +} + +class _ConvertPrivateKeyRequestReader + extends fb.TableReader { + const _ConvertPrivateKeyRequestReader(); + + @override + ConvertPrivateKeyRequest createObject(fb.BufferContext bc, int offset) => + ConvertPrivateKeyRequest._(bc, offset); +} + +class ConvertPrivateKeyRequestBuilder { + ConvertPrivateKeyRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class ConvertPrivateKeyRequestObjectBuilder extends fb.ObjectBuilder { + final String? _privateKey; + + ConvertPrivateKeyRequestObjectBuilder({ + String? privateKey, + }) : _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class ConvertPublicKeyRequest { + ConvertPublicKeyRequest._(this._bc, this._bcOffset); + factory ConvertPublicKeyRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _ConvertPublicKeyRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'ConvertPublicKeyRequest{publicKey: $publicKey}'; + } +} + +class _ConvertPublicKeyRequestReader + extends fb.TableReader { + const _ConvertPublicKeyRequestReader(); + + @override + ConvertPublicKeyRequest createObject(fb.BufferContext bc, int offset) => + ConvertPublicKeyRequest._(bc, offset); +} + +class ConvertPublicKeyRequestBuilder { + ConvertPublicKeyRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class ConvertPublicKeyRequestObjectBuilder extends fb.ObjectBuilder { + final String? _publicKey; + + ConvertPublicKeyRequestObjectBuilder({ + String? publicKey, + }) : _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class DecryptOAEPRequest { + DecryptOAEPRequest._(this._bc, this._bcOffset); + factory DecryptOAEPRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _DecryptOAEPRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get ciphertext => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get label => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + + @override + String toString() { + return 'DecryptOAEPRequest{ciphertext: $ciphertext, label: $label, hash: $hash, privateKey: $privateKey}'; + } +} + +class _DecryptOAEPRequestReader extends fb.TableReader { + const _DecryptOAEPRequestReader(); + + @override + DecryptOAEPRequest createObject(fb.BufferContext bc, int offset) => + DecryptOAEPRequest._(bc, offset); +} + +class DecryptOAEPRequestBuilder { + DecryptOAEPRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addCiphertextOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addLabelOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(2, hash?.value); + return fbBuilder.offset; + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class DecryptOAEPRequestObjectBuilder extends fb.ObjectBuilder { + final String? _ciphertext; + final String? _label; + final Hash? _hash; + final String? _privateKey; + + DecryptOAEPRequestObjectBuilder({ + String? ciphertext, + String? label, + Hash? hash, + String? privateKey, + }) : _ciphertext = ciphertext, + _label = label, + _hash = hash, + _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? ciphertextOffset = + _ciphertext == null ? null : fbBuilder.writeString(_ciphertext!); + final int? labelOffset = + _label == null ? null : fbBuilder.writeString(_label!); + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(4); + fbBuilder.addOffset(0, ciphertextOffset); + fbBuilder.addOffset(1, labelOffset); + fbBuilder.addInt32(2, _hash?.value); + fbBuilder.addOffset(3, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class DecryptOAEPBytesRequest { + DecryptOAEPBytesRequest._(this._bc, this._bcOffset); + factory DecryptOAEPBytesRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _DecryptOAEPBytesRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get ciphertext => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get label => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + + @override + String toString() { + return 'DecryptOAEPBytesRequest{ciphertext: $ciphertext, label: $label, hash: $hash, privateKey: $privateKey}'; + } +} + +class _DecryptOAEPBytesRequestReader + extends fb.TableReader { + const _DecryptOAEPBytesRequestReader(); + + @override + DecryptOAEPBytesRequest createObject(fb.BufferContext bc, int offset) => + DecryptOAEPBytesRequest._(bc, offset); +} + +class DecryptOAEPBytesRequestBuilder { + DecryptOAEPBytesRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addCiphertextOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addLabelOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(2, hash?.value); + return fbBuilder.offset; + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class DecryptOAEPBytesRequestObjectBuilder extends fb.ObjectBuilder { + final List? _ciphertext; + final String? _label; + final Hash? _hash; + final String? _privateKey; + + DecryptOAEPBytesRequestObjectBuilder({ + List? ciphertext, + String? label, + Hash? hash, + String? privateKey, + }) : _ciphertext = ciphertext, + _label = label, + _hash = hash, + _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? ciphertextOffset = + _ciphertext == null ? null : fbBuilder.writeListUint8(_ciphertext!); + final int? labelOffset = + _label == null ? null : fbBuilder.writeString(_label!); + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(4); + fbBuilder.addOffset(0, ciphertextOffset); + fbBuilder.addOffset(1, labelOffset); + fbBuilder.addInt32(2, _hash?.value); + fbBuilder.addOffset(3, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class DecryptPKCS1v15Request { + DecryptPKCS1v15Request._(this._bc, this._bcOffset); + factory DecryptPKCS1v15Request(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _DecryptPKCS1v15RequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get ciphertext => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'DecryptPKCS1v15Request{ciphertext: $ciphertext, privateKey: $privateKey}'; + } +} + +class _DecryptPKCS1v15RequestReader + extends fb.TableReader { + const _DecryptPKCS1v15RequestReader(); + + @override + DecryptPKCS1v15Request createObject(fb.BufferContext bc, int offset) => + DecryptPKCS1v15Request._(bc, offset); +} + +class DecryptPKCS1v15RequestBuilder { + DecryptPKCS1v15RequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addCiphertextOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class DecryptPKCS1v15RequestObjectBuilder extends fb.ObjectBuilder { + final String? _ciphertext; + final String? _privateKey; + + DecryptPKCS1v15RequestObjectBuilder({ + String? ciphertext, + String? privateKey, + }) : _ciphertext = ciphertext, + _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? ciphertextOffset = + _ciphertext == null ? null : fbBuilder.writeString(_ciphertext!); + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, ciphertextOffset); + fbBuilder.addOffset(1, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class DecryptPKCS1v15BytesRequest { + DecryptPKCS1v15BytesRequest._(this._bc, this._bcOffset); + factory DecryptPKCS1v15BytesRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _DecryptPKCS1v15BytesRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get ciphertext => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'DecryptPKCS1v15BytesRequest{ciphertext: $ciphertext, privateKey: $privateKey}'; + } +} + +class _DecryptPKCS1v15BytesRequestReader + extends fb.TableReader { + const _DecryptPKCS1v15BytesRequestReader(); + + @override + DecryptPKCS1v15BytesRequest createObject(fb.BufferContext bc, int offset) => + DecryptPKCS1v15BytesRequest._(bc, offset); +} + +class DecryptPKCS1v15BytesRequestBuilder { + DecryptPKCS1v15BytesRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addCiphertextOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class DecryptPKCS1v15BytesRequestObjectBuilder extends fb.ObjectBuilder { + final List? _ciphertext; + final String? _privateKey; + + DecryptPKCS1v15BytesRequestObjectBuilder({ + List? ciphertext, + String? privateKey, + }) : _ciphertext = ciphertext, + _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? ciphertextOffset = + _ciphertext == null ? null : fbBuilder.writeListUint8(_ciphertext!); + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, ciphertextOffset); + fbBuilder.addOffset(1, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class DecryptPrivateKeyRequest { + DecryptPrivateKeyRequest._(this._bc, this._bcOffset); + factory DecryptPrivateKeyRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _DecryptPrivateKeyRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get privateKeyEncrypted => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get password => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'DecryptPrivateKeyRequest{privateKeyEncrypted: $privateKeyEncrypted, password: $password}'; + } +} + +class _DecryptPrivateKeyRequestReader + extends fb.TableReader { + const _DecryptPrivateKeyRequestReader(); + + @override + DecryptPrivateKeyRequest createObject(fb.BufferContext bc, int offset) => + DecryptPrivateKeyRequest._(bc, offset); +} + +class DecryptPrivateKeyRequestBuilder { + DecryptPrivateKeyRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addPrivateKeyEncryptedOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPasswordOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class DecryptPrivateKeyRequestObjectBuilder extends fb.ObjectBuilder { + final String? _privateKeyEncrypted; + final String? _password; + + DecryptPrivateKeyRequestObjectBuilder({ + String? privateKeyEncrypted, + String? password, + }) : _privateKeyEncrypted = privateKeyEncrypted, + _password = password; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? privateKeyEncryptedOffset = _privateKeyEncrypted == null + ? null + : fbBuilder.writeString(_privateKeyEncrypted!); + final int? passwordOffset = + _password == null ? null : fbBuilder.writeString(_password!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, privateKeyEncryptedOffset); + fbBuilder.addOffset(1, passwordOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class EncryptOAEPRequest { + EncryptOAEPRequest._(this._bc, this._bcOffset); + factory EncryptOAEPRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _EncryptOAEPRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get message => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get label => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + + @override + String toString() { + return 'EncryptOAEPRequest{message: $message, label: $label, hash: $hash, publicKey: $publicKey}'; + } +} + +class _EncryptOAEPRequestReader extends fb.TableReader { + const _EncryptOAEPRequestReader(); + + @override + EncryptOAEPRequest createObject(fb.BufferContext bc, int offset) => + EncryptOAEPRequest._(bc, offset); +} + +class EncryptOAEPRequestBuilder { + EncryptOAEPRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addLabelOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(2, hash?.value); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class EncryptOAEPRequestObjectBuilder extends fb.ObjectBuilder { + final String? _message; + final String? _label; + final Hash? _hash; + final String? _publicKey; + + EncryptOAEPRequestObjectBuilder({ + String? message, + String? label, + Hash? hash, + String? publicKey, + }) : _message = message, + _label = label, + _hash = hash, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeString(_message!); + final int? labelOffset = + _label == null ? null : fbBuilder.writeString(_label!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(4); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addOffset(1, labelOffset); + fbBuilder.addInt32(2, _hash?.value); + fbBuilder.addOffset(3, publicKeyOffset); + + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class EncryptOAEPBytesRequest { + EncryptOAEPBytesRequest._(this._bc, this._bcOffset); + factory EncryptOAEPBytesRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _EncryptOAEPBytesRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get message => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get label => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + + @override + String toString() { + return 'EncryptOAEPBytesRequest{message: $message, label: $label, hash: $hash, publicKey: $publicKey}'; + } +} + +class _EncryptOAEPBytesRequestReader + extends fb.TableReader { + const _EncryptOAEPBytesRequestReader(); + + @override + EncryptOAEPBytesRequest createObject(fb.BufferContext bc, int offset) => + EncryptOAEPBytesRequest._(bc, offset); +} + +class EncryptOAEPBytesRequestBuilder { + EncryptOAEPBytesRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addLabelOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(2, hash?.value); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class EncryptOAEPBytesRequestObjectBuilder extends fb.ObjectBuilder { + final List? _message; + final String? _label; + final Hash? _hash; + final String? _publicKey; + + EncryptOAEPBytesRequestObjectBuilder({ + List? message, + String? label, + Hash? hash, + String? publicKey, + }) : _message = message, + _label = label, + _hash = hash, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeListUint8(_message!); + final int? labelOffset = + _label == null ? null : fbBuilder.writeString(_label!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(4); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addOffset(1, labelOffset); + fbBuilder.addInt32(2, _hash?.value); + fbBuilder.addOffset(3, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class EncryptPKCS1v15Request { + EncryptPKCS1v15Request._(this._bc, this._bcOffset); + factory EncryptPKCS1v15Request(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _EncryptPKCS1v15RequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get message => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'EncryptPKCS1v15Request{message: $message, publicKey: $publicKey}'; + } +} + +class _EncryptPKCS1v15RequestReader + extends fb.TableReader { + const _EncryptPKCS1v15RequestReader(); + + @override + EncryptPKCS1v15Request createObject(fb.BufferContext bc, int offset) => + EncryptPKCS1v15Request._(bc, offset); +} + +class EncryptPKCS1v15RequestBuilder { + EncryptPKCS1v15RequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class EncryptPKCS1v15RequestObjectBuilder extends fb.ObjectBuilder { + final String? _message; + final String? _publicKey; + + EncryptPKCS1v15RequestObjectBuilder({ + String? message, + String? publicKey, + }) : _message = message, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeString(_message!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addOffset(1, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class EncryptPKCS1v15BytesRequest { + EncryptPKCS1v15BytesRequest._(this._bc, this._bcOffset); + factory EncryptPKCS1v15BytesRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _EncryptPKCS1v15BytesRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get message => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'EncryptPKCS1v15BytesRequest{message: $message, publicKey: $publicKey}'; + } +} + +class _EncryptPKCS1v15BytesRequestReader + extends fb.TableReader { + const _EncryptPKCS1v15BytesRequestReader(); + + @override + EncryptPKCS1v15BytesRequest createObject(fb.BufferContext bc, int offset) => + EncryptPKCS1v15BytesRequest._(bc, offset); +} + +class EncryptPKCS1v15BytesRequestBuilder { + EncryptPKCS1v15BytesRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class EncryptPKCS1v15BytesRequestObjectBuilder extends fb.ObjectBuilder { + final List? _message; + final String? _publicKey; + + EncryptPKCS1v15BytesRequestObjectBuilder({ + List? message, + String? publicKey, + }) : _message = message, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeListUint8(_message!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addOffset(1, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class EncryptPrivateKeyRequest { + EncryptPrivateKeyRequest._(this._bc, this._bcOffset); + factory EncryptPrivateKeyRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _EncryptPrivateKeyRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get password => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + PEMCipher get cipher => PEMCipher.fromValue( + const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + + @override + String toString() { + return 'EncryptPrivateKeyRequest{privateKey: $privateKey, password: $password, cipher: $cipher}'; + } +} + +class _EncryptPrivateKeyRequestReader + extends fb.TableReader { + const _EncryptPrivateKeyRequestReader(); + + @override + EncryptPrivateKeyRequest createObject(fb.BufferContext bc, int offset) => + EncryptPrivateKeyRequest._(bc, offset); +} + +class EncryptPrivateKeyRequestBuilder { + EncryptPrivateKeyRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPasswordOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addCipher(PEMCipher? cipher) { + fbBuilder.addInt32(2, cipher?.value); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class EncryptPrivateKeyRequestObjectBuilder extends fb.ObjectBuilder { + final String? _privateKey; + final String? _password; + final PEMCipher? _cipher; + + EncryptPrivateKeyRequestObjectBuilder({ + String? privateKey, + String? password, + PEMCipher? cipher, + }) : _privateKey = privateKey, + _password = password, + _cipher = cipher; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + final int? passwordOffset = + _password == null ? null : fbBuilder.writeString(_password!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, privateKeyOffset); + fbBuilder.addOffset(1, passwordOffset); + fbBuilder.addInt32(2, _cipher?.value); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class GenerateRequest { + GenerateRequest._(this._bc, this._bcOffset); + factory GenerateRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _GenerateRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get nBits => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 4, 0); + + @override + String toString() { + return 'GenerateRequest{nBits: $nBits}'; + } +} + +class _GenerateRequestReader extends fb.TableReader { + const _GenerateRequestReader(); + + @override + GenerateRequest createObject(fb.BufferContext bc, int offset) => + GenerateRequest._(bc, offset); +} + +class GenerateRequestBuilder { + GenerateRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addNBits(int? nBits) { + fbBuilder.addInt32(0, nBits); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class GenerateRequestObjectBuilder extends fb.ObjectBuilder { + final int? _nBits; + + GenerateRequestObjectBuilder({ + int? nBits, + }) : _nBits = nBits; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addInt32(0, _nBits); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class HashRequest { + HashRequest._(this._bc, this._bcOffset); + factory HashRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _HashRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get message => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 6, 0)); + + @override + String toString() { + return 'HashRequest{message: $message, hash: $hash}'; + } +} + +class _HashRequestReader extends fb.TableReader { + const _HashRequestReader(); + + @override + HashRequest createObject(fb.BufferContext bc, int offset) => + HashRequest._(bc, offset); +} + +class HashRequestBuilder { + HashRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(1, hash?.value); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class HashRequestObjectBuilder extends fb.ObjectBuilder { + final String? _message; + final Hash? _hash; + + HashRequestObjectBuilder({ + String? message, + Hash? hash, + }) : _message = message, + _hash = hash; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeString(_message!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addInt32(1, _hash?.value); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class Base64Request { + Base64Request._(this._bc, this._bcOffset); + factory Base64Request(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _Base64RequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get message => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'Base64Request{message: $message}'; + } +} + +class _Base64RequestReader extends fb.TableReader { + const _Base64RequestReader(); + + @override + Base64Request createObject(fb.BufferContext bc, int offset) => + Base64Request._(bc, offset); +} + +class Base64RequestBuilder { + Base64RequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class Base64RequestObjectBuilder extends fb.ObjectBuilder { + final String? _message; + + Base64RequestObjectBuilder({ + String? message, + }) : _message = message; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeString(_message!); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, messageOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class MetadataPrivateKeyRequest { + MetadataPrivateKeyRequest._(this._bc, this._bcOffset); + factory MetadataPrivateKeyRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _MetadataPrivateKeyRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'MetadataPrivateKeyRequest{privateKey: $privateKey}'; + } +} + +class _MetadataPrivateKeyRequestReader + extends fb.TableReader { + const _MetadataPrivateKeyRequestReader(); + + @override + MetadataPrivateKeyRequest createObject(fb.BufferContext bc, int offset) => + MetadataPrivateKeyRequest._(bc, offset); +} + +class MetadataPrivateKeyRequestBuilder { + MetadataPrivateKeyRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class MetadataPrivateKeyRequestObjectBuilder extends fb.ObjectBuilder { + final String? _privateKey; + + MetadataPrivateKeyRequestObjectBuilder({ + String? privateKey, + }) : _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class MetadataPublicKeyRequest { + MetadataPublicKeyRequest._(this._bc, this._bcOffset); + factory MetadataPublicKeyRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _MetadataPublicKeyRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'MetadataPublicKeyRequest{publicKey: $publicKey}'; + } +} + +class _MetadataPublicKeyRequestReader + extends fb.TableReader { + const _MetadataPublicKeyRequestReader(); + + @override + MetadataPublicKeyRequest createObject(fb.BufferContext bc, int offset) => + MetadataPublicKeyRequest._(bc, offset); +} + +class MetadataPublicKeyRequestBuilder { + MetadataPublicKeyRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class MetadataPublicKeyRequestObjectBuilder extends fb.ObjectBuilder { + final String? _publicKey; + + MetadataPublicKeyRequestObjectBuilder({ + String? publicKey, + }) : _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class SignPKCS1v15Request { + SignPKCS1v15Request._(this._bc, this._bcOffset); + factory SignPKCS1v15Request(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _SignPKCS1v15RequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get message => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 6, 0)); + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 8); + + @override + String toString() { + return 'SignPKCS1v15Request{message: $message, hash: $hash, privateKey: $privateKey}'; + } +} + +class _SignPKCS1v15RequestReader extends fb.TableReader { + const _SignPKCS1v15RequestReader(); + + @override + SignPKCS1v15Request createObject(fb.BufferContext bc, int offset) => + SignPKCS1v15Request._(bc, offset); +} + +class SignPKCS1v15RequestBuilder { + SignPKCS1v15RequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(1, hash?.value); + return fbBuilder.offset; + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(2, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class SignPKCS1v15RequestObjectBuilder extends fb.ObjectBuilder { + final String? _message; + final Hash? _hash; + final String? _privateKey; + + SignPKCS1v15RequestObjectBuilder({ + String? message, + Hash? hash, + String? privateKey, + }) : _message = message, + _hash = hash, + _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeString(_message!); + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addInt32(1, _hash?.value); + fbBuilder.addOffset(2, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class SignPKCS1v15BytesRequest { + SignPKCS1v15BytesRequest._(this._bc, this._bcOffset); + factory SignPKCS1v15BytesRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _SignPKCS1v15BytesRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get message => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 6, 0)); + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 8); + + @override + String toString() { + return 'SignPKCS1v15BytesRequest{message: $message, hash: $hash, privateKey: $privateKey}'; + } +} + +class _SignPKCS1v15BytesRequestReader + extends fb.TableReader { + const _SignPKCS1v15BytesRequestReader(); + + @override + SignPKCS1v15BytesRequest createObject(fb.BufferContext bc, int offset) => + SignPKCS1v15BytesRequest._(bc, offset); +} + +class SignPKCS1v15BytesRequestBuilder { + SignPKCS1v15BytesRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(1, hash?.value); + return fbBuilder.offset; + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(2, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class SignPKCS1v15BytesRequestObjectBuilder extends fb.ObjectBuilder { + final List? _message; + final Hash? _hash; + final String? _privateKey; + + SignPKCS1v15BytesRequestObjectBuilder({ + List? message, + Hash? hash, + String? privateKey, + }) : _message = message, + _hash = hash, + _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeListUint8(_message!); + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addInt32(1, _hash?.value); + fbBuilder.addOffset(2, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class SignPSSRequest { + SignPSSRequest._(this._bc, this._bcOffset); + factory SignPSSRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _SignPSSRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get message => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 6, 0)); + SaltLength get saltLength => SaltLength.fromValue( + const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + + @override + String toString() { + return 'SignPSSRequest{message: $message, hash: $hash, saltLength: $saltLength, privateKey: $privateKey}'; + } +} + +class _SignPSSRequestReader extends fb.TableReader { + const _SignPSSRequestReader(); + + @override + SignPSSRequest createObject(fb.BufferContext bc, int offset) => + SignPSSRequest._(bc, offset); +} + +class SignPSSRequestBuilder { + SignPSSRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(1, hash?.value); + return fbBuilder.offset; + } + + int addSaltLength(SaltLength? saltLength) { + fbBuilder.addInt32(2, saltLength?.value); + return fbBuilder.offset; + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class SignPSSRequestObjectBuilder extends fb.ObjectBuilder { + final String? _message; + final Hash? _hash; + final SaltLength? _saltLength; + final String? _privateKey; + + SignPSSRequestObjectBuilder({ + String? message, + Hash? hash, + SaltLength? saltLength, + String? privateKey, + }) : _message = message, + _hash = hash, + _saltLength = saltLength, + _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeString(_message!); + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(4); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addInt32(1, _hash?.value); + fbBuilder.addInt32(2, _saltLength?.value); + fbBuilder.addOffset(3, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class SignPSSBytesRequest { + SignPSSBytesRequest._(this._bc, this._bcOffset); + factory SignPSSBytesRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _SignPSSBytesRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get message => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 6, 0)); + SaltLength get saltLength => SaltLength.fromValue( + const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + + @override + String toString() { + return 'SignPSSBytesRequest{message: $message, hash: $hash, saltLength: $saltLength, privateKey: $privateKey}'; + } +} + +class _SignPSSBytesRequestReader extends fb.TableReader { + const _SignPSSBytesRequestReader(); + + @override + SignPSSBytesRequest createObject(fb.BufferContext bc, int offset) => + SignPSSBytesRequest._(bc, offset); +} + +class SignPSSBytesRequestBuilder { + SignPSSBytesRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(1, hash?.value); + return fbBuilder.offset; + } + + int addSaltLength(SaltLength? saltLength) { + fbBuilder.addInt32(2, saltLength?.value); + return fbBuilder.offset; + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class SignPSSBytesRequestObjectBuilder extends fb.ObjectBuilder { + final List? _message; + final Hash? _hash; + final SaltLength? _saltLength; + final String? _privateKey; + + SignPSSBytesRequestObjectBuilder({ + List? message, + Hash? hash, + SaltLength? saltLength, + String? privateKey, + }) : _message = message, + _hash = hash, + _saltLength = saltLength, + _privateKey = privateKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? messageOffset = + _message == null ? null : fbBuilder.writeListUint8(_message!); + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + fbBuilder.startTable(4); + fbBuilder.addOffset(0, messageOffset); + fbBuilder.addInt32(1, _hash?.value); + fbBuilder.addInt32(2, _saltLength?.value); + fbBuilder.addOffset(3, privateKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class VerifyPKCS1v15Request { + VerifyPKCS1v15Request._(this._bc, this._bcOffset); + factory VerifyPKCS1v15Request(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _VerifyPKCS1v15RequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get signature => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get message => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + + @override + String toString() { + return 'VerifyPKCS1v15Request{signature: $signature, message: $message, hash: $hash, publicKey: $publicKey}'; + } +} + +class _VerifyPKCS1v15RequestReader + extends fb.TableReader { + const _VerifyPKCS1v15RequestReader(); + + @override + VerifyPKCS1v15Request createObject(fb.BufferContext bc, int offset) => + VerifyPKCS1v15Request._(bc, offset); +} + +class VerifyPKCS1v15RequestBuilder { + VerifyPKCS1v15RequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addSignatureOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(2, hash?.value); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class VerifyPKCS1v15RequestObjectBuilder extends fb.ObjectBuilder { + final String? _signature; + final String? _message; + final Hash? _hash; + final String? _publicKey; + + VerifyPKCS1v15RequestObjectBuilder({ + String? signature, + String? message, + Hash? hash, + String? publicKey, + }) : _signature = signature, + _message = message, + _hash = hash, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? signatureOffset = + _signature == null ? null : fbBuilder.writeString(_signature!); + final int? messageOffset = + _message == null ? null : fbBuilder.writeString(_message!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(4); + fbBuilder.addOffset(0, signatureOffset); + fbBuilder.addOffset(1, messageOffset); + fbBuilder.addInt32(2, _hash?.value); + fbBuilder.addOffset(3, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class VerifyPKCS1v15BytesRequest { + VerifyPKCS1v15BytesRequest._(this._bc, this._bcOffset); + factory VerifyPKCS1v15BytesRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _VerifyPKCS1v15BytesRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get signature => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + List? get message => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 6); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + + @override + String toString() { + return 'VerifyPKCS1v15BytesRequest{signature: $signature, message: $message, hash: $hash, publicKey: $publicKey}'; + } +} + +class _VerifyPKCS1v15BytesRequestReader + extends fb.TableReader { + const _VerifyPKCS1v15BytesRequestReader(); + + @override + VerifyPKCS1v15BytesRequest createObject(fb.BufferContext bc, int offset) => + VerifyPKCS1v15BytesRequest._(bc, offset); +} + +class VerifyPKCS1v15BytesRequestBuilder { + VerifyPKCS1v15BytesRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addSignatureOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(2, hash?.value); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class VerifyPKCS1v15BytesRequestObjectBuilder extends fb.ObjectBuilder { + final List? _signature; + final List? _message; + final Hash? _hash; + final String? _publicKey; + + VerifyPKCS1v15BytesRequestObjectBuilder({ + List? signature, + List? message, + Hash? hash, + String? publicKey, + }) : _signature = signature, + _message = message, + _hash = hash, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? signatureOffset = + _signature == null ? null : fbBuilder.writeListUint8(_signature!); + final int? messageOffset = + _message == null ? null : fbBuilder.writeListUint8(_message!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(4); + fbBuilder.addOffset(0, signatureOffset); + fbBuilder.addOffset(1, messageOffset); + fbBuilder.addInt32(2, _hash?.value); + fbBuilder.addOffset(3, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class VerifyPSSRequest { + VerifyPSSRequest._(this._bc, this._bcOffset); + factory VerifyPSSRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _VerifyPSSRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get signature => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get message => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + SaltLength get saltLength => SaltLength.fromValue( + const fb.Int32Reader().vTableGet(_bc, _bcOffset, 10, 0)); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 12); + + @override + String toString() { + return 'VerifyPSSRequest{signature: $signature, message: $message, hash: $hash, saltLength: $saltLength, publicKey: $publicKey}'; + } +} + +class _VerifyPSSRequestReader extends fb.TableReader { + const _VerifyPSSRequestReader(); + + @override + VerifyPSSRequest createObject(fb.BufferContext bc, int offset) => + VerifyPSSRequest._(bc, offset); +} + +class VerifyPSSRequestBuilder { + VerifyPSSRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(5); + } + + int addSignatureOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(2, hash?.value); + return fbBuilder.offset; + } + + int addSaltLength(SaltLength? saltLength) { + fbBuilder.addInt32(3, saltLength?.value); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(4, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class VerifyPSSRequestObjectBuilder extends fb.ObjectBuilder { + final String? _signature; + final String? _message; + final Hash? _hash; + final SaltLength? _saltLength; + final String? _publicKey; + + VerifyPSSRequestObjectBuilder({ + String? signature, + String? message, + Hash? hash, + SaltLength? saltLength, + String? publicKey, + }) : _signature = signature, + _message = message, + _hash = hash, + _saltLength = saltLength, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? signatureOffset = + _signature == null ? null : fbBuilder.writeString(_signature!); + final int? messageOffset = + _message == null ? null : fbBuilder.writeString(_message!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(5); + fbBuilder.addOffset(0, signatureOffset); + fbBuilder.addOffset(1, messageOffset); + fbBuilder.addInt32(2, _hash?.value); + fbBuilder.addInt32(3, _saltLength?.value); + fbBuilder.addOffset(4, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class VerifyPSSBytesRequest { + VerifyPSSBytesRequest._(this._bc, this._bcOffset); + factory VerifyPSSBytesRequest(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _VerifyPSSBytesRequestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get signature => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + List? get message => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 6); + Hash get hash => + Hash.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0)); + SaltLength get saltLength => SaltLength.fromValue( + const fb.Int32Reader().vTableGet(_bc, _bcOffset, 10, 0)); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 12); + + @override + String toString() { + return 'VerifyPSSBytesRequest{signature: $signature, message: $message, hash: $hash, saltLength: $saltLength, publicKey: $publicKey}'; + } +} + +class _VerifyPSSBytesRequestReader + extends fb.TableReader { + const _VerifyPSSBytesRequestReader(); + + @override + VerifyPSSBytesRequest createObject(fb.BufferContext bc, int offset) => + VerifyPSSBytesRequest._(bc, offset); +} + +class VerifyPSSBytesRequestBuilder { + VerifyPSSBytesRequestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(5); + } + + int addSignatureOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addMessageOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addHash(Hash? hash) { + fbBuilder.addInt32(2, hash?.value); + return fbBuilder.offset; + } + + int addSaltLength(SaltLength? saltLength) { + fbBuilder.addInt32(3, saltLength?.value); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(4, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class VerifyPSSBytesRequestObjectBuilder extends fb.ObjectBuilder { + final List? _signature; + final List? _message; + final Hash? _hash; + final SaltLength? _saltLength; + final String? _publicKey; + + VerifyPSSBytesRequestObjectBuilder({ + List? signature, + List? message, + Hash? hash, + SaltLength? saltLength, + String? publicKey, + }) : _signature = signature, + _message = message, + _hash = hash, + _saltLength = saltLength, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? signatureOffset = + _signature == null ? null : fbBuilder.writeListUint8(_signature!); + final int? messageOffset = + _message == null ? null : fbBuilder.writeListUint8(_message!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(5); + fbBuilder.addOffset(0, signatureOffset); + fbBuilder.addOffset(1, messageOffset); + fbBuilder.addInt32(2, _hash?.value); + fbBuilder.addInt32(3, _saltLength?.value); + fbBuilder.addOffset(4, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class StringResponse { + StringResponse._(this._bc, this._bcOffset); + factory StringResponse(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _StringResponseReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get output => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get error => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'StringResponse{output: $output, error: $error}'; + } +} + +class _StringResponseReader extends fb.TableReader { + const _StringResponseReader(); + + @override + StringResponse createObject(fb.BufferContext bc, int offset) => + StringResponse._(bc, offset); +} + +class StringResponseBuilder { + StringResponseBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addOutputOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addErrorOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class StringResponseObjectBuilder extends fb.ObjectBuilder { + final String? _output; + final String? _error; + + StringResponseObjectBuilder({ + String? output, + String? error, + }) : _output = output, + _error = error; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? outputOffset = + _output == null ? null : fbBuilder.writeString(_output!); + final int? errorOffset = + _error == null ? null : fbBuilder.writeString(_error!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, outputOffset); + fbBuilder.addOffset(1, errorOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class BytesResponse { + BytesResponse._(this._bc, this._bcOffset); + factory BytesResponse(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _BytesResponseReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get output => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get error => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'BytesResponse{output: $output, error: $error}'; + } +} + +class _BytesResponseReader extends fb.TableReader { + const _BytesResponseReader(); + + @override + BytesResponse createObject(fb.BufferContext bc, int offset) => + BytesResponse._(bc, offset); +} + +class BytesResponseBuilder { + BytesResponseBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addOutputOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addErrorOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class BytesResponseObjectBuilder extends fb.ObjectBuilder { + final List? _output; + final String? _error; + + BytesResponseObjectBuilder({ + List? output, + String? error, + }) : _output = output, + _error = error; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? outputOffset = + _output == null ? null : fbBuilder.writeListUint8(_output!); + final int? errorOffset = + _error == null ? null : fbBuilder.writeString(_error!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, outputOffset); + fbBuilder.addOffset(1, errorOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class BoolResponse { + BoolResponse._(this._bc, this._bcOffset); + factory BoolResponse(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _BoolResponseReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + bool get output => const fb.BoolReader().vTableGet(_bc, _bcOffset, 4, false); + String? get error => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'BoolResponse{output: $output, error: $error}'; + } +} + +class _BoolResponseReader extends fb.TableReader { + const _BoolResponseReader(); + + @override + BoolResponse createObject(fb.BufferContext bc, int offset) => + BoolResponse._(bc, offset); +} + +class BoolResponseBuilder { + BoolResponseBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addOutput(bool? output) { + fbBuilder.addBool(0, output); + return fbBuilder.offset; + } + + int addErrorOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class BoolResponseObjectBuilder extends fb.ObjectBuilder { + final bool? _output; + final String? _error; + + BoolResponseObjectBuilder({ + bool? output, + String? error, + }) : _output = output, + _error = error; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? errorOffset = + _error == null ? null : fbBuilder.writeString(_error!); + fbBuilder.startTable(2); + fbBuilder.addBool(0, _output); + fbBuilder.addOffset(1, errorOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class PKCS12KeyPairResponse { + PKCS12KeyPairResponse._(this._bc, this._bcOffset); + factory PKCS12KeyPairResponse(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _PKCS12KeyPairResponseReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + PKCS12KeyPair? get output => + PKCS12KeyPair.reader.vTableGetNullable(_bc, _bcOffset, 4); + String? get error => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'PKCS12KeyPairResponse{output: $output, error: $error}'; + } +} + +class _PKCS12KeyPairResponseReader + extends fb.TableReader { + const _PKCS12KeyPairResponseReader(); + + @override + PKCS12KeyPairResponse createObject(fb.BufferContext bc, int offset) => + PKCS12KeyPairResponse._(bc, offset); +} + +class PKCS12KeyPairResponseBuilder { + PKCS12KeyPairResponseBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addOutputOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addErrorOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class PKCS12KeyPairResponseObjectBuilder extends fb.ObjectBuilder { + final PKCS12KeyPairObjectBuilder? _output; + final String? _error; + + PKCS12KeyPairResponseObjectBuilder({ + PKCS12KeyPairObjectBuilder? output, + String? error, + }) : _output = output, + _error = error; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? outputOffset = _output?.getOrCreateOffset(fbBuilder); + final int? errorOffset = + _error == null ? null : fbBuilder.writeString(_error!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, outputOffset); + fbBuilder.addOffset(1, errorOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class PKCS12KeyPair { + PKCS12KeyPair._(this._bc, this._bcOffset); + factory PKCS12KeyPair(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _PKCS12KeyPairReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + String? get certificate => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 8); + + @override + String toString() { + return 'PKCS12KeyPair{privateKey: $privateKey, publicKey: $publicKey, certificate: $certificate}'; + } +} + +class _PKCS12KeyPairReader extends fb.TableReader { + const _PKCS12KeyPairReader(); + + @override + PKCS12KeyPair createObject(fb.BufferContext bc, int offset) => + PKCS12KeyPair._(bc, offset); +} + +class PKCS12KeyPairBuilder { + PKCS12KeyPairBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int addCertificateOffset(int? offset) { + fbBuilder.addOffset(2, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class PKCS12KeyPairObjectBuilder extends fb.ObjectBuilder { + final String? _privateKey; + final String? _publicKey; + final String? _certificate; + + PKCS12KeyPairObjectBuilder({ + String? privateKey, + String? publicKey, + String? certificate, + }) : _privateKey = privateKey, + _publicKey = publicKey, + _certificate = certificate; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + final int? certificateOffset = + _certificate == null ? null : fbBuilder.writeString(_certificate!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, privateKeyOffset); + fbBuilder.addOffset(1, publicKeyOffset); + fbBuilder.addOffset(2, certificateOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class KeyPairResponse { + KeyPairResponse._(this._bc, this._bcOffset); + factory KeyPairResponse(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _KeyPairResponseReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + KeyPair? get output => KeyPair.reader.vTableGetNullable(_bc, _bcOffset, 4); + String? get error => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'KeyPairResponse{output: $output, error: $error}'; + } +} + +class _KeyPairResponseReader extends fb.TableReader { + const _KeyPairResponseReader(); + + @override + KeyPairResponse createObject(fb.BufferContext bc, int offset) => + KeyPairResponse._(bc, offset); +} + +class KeyPairResponseBuilder { + KeyPairResponseBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addOutputOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addErrorOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class KeyPairResponseObjectBuilder extends fb.ObjectBuilder { + final KeyPairObjectBuilder? _output; + final String? _error; + + KeyPairResponseObjectBuilder({ + KeyPairObjectBuilder? output, + String? error, + }) : _output = output, + _error = error; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? outputOffset = _output?.getOrCreateOffset(fbBuilder); + final int? errorOffset = + _error == null ? null : fbBuilder.writeString(_error!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, outputOffset); + fbBuilder.addOffset(1, errorOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class KeyPair { + KeyPair._(this._bc, this._bcOffset); + factory KeyPair(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _KeyPairReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get privateKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get publicKey => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'KeyPair{privateKey: $privateKey, publicKey: $publicKey}'; + } +} + +class _KeyPairReader extends fb.TableReader { + const _KeyPairReader(); + + @override + KeyPair createObject(fb.BufferContext bc, int offset) => + KeyPair._(bc, offset); +} + +class KeyPairBuilder { + KeyPairBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addPrivateKeyOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addPublicKeyOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class KeyPairObjectBuilder extends fb.ObjectBuilder { + final String? _privateKey; + final String? _publicKey; + + KeyPairObjectBuilder({ + String? privateKey, + String? publicKey, + }) : _privateKey = privateKey, + _publicKey = publicKey; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? privateKeyOffset = + _privateKey == null ? null : fbBuilder.writeString(_privateKey!); + final int? publicKeyOffset = + _publicKey == null ? null : fbBuilder.writeString(_publicKey!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, privateKeyOffset); + fbBuilder.addOffset(1, publicKeyOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class PrivateKeyInfoResponse { + PrivateKeyInfoResponse._(this._bc, this._bcOffset); + factory PrivateKeyInfoResponse(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _PrivateKeyInfoResponseReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + PrivateKeyInfo? get output => + PrivateKeyInfo.reader.vTableGetNullable(_bc, _bcOffset, 4); + String? get error => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'PrivateKeyInfoResponse{output: $output, error: $error}'; + } +} + +class _PrivateKeyInfoResponseReader + extends fb.TableReader { + const _PrivateKeyInfoResponseReader(); + + @override + PrivateKeyInfoResponse createObject(fb.BufferContext bc, int offset) => + PrivateKeyInfoResponse._(bc, offset); +} + +class PrivateKeyInfoResponseBuilder { + PrivateKeyInfoResponseBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addOutputOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addErrorOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class PrivateKeyInfoResponseObjectBuilder extends fb.ObjectBuilder { + final PrivateKeyInfoObjectBuilder? _output; + final String? _error; + + PrivateKeyInfoResponseObjectBuilder({ + PrivateKeyInfoObjectBuilder? output, + String? error, + }) : _output = output, + _error = error; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? outputOffset = _output?.getOrCreateOffset(fbBuilder); + final int? errorOffset = + _error == null ? null : fbBuilder.writeString(_error!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, outputOffset); + fbBuilder.addOffset(1, errorOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class PrivateKeyInfo { + PrivateKeyInfo._(this._bc, this._bcOffset); + factory PrivateKeyInfo(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _PrivateKeyInfoReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get bitLen => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 4, 0); + int get size => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 6, 0); + String? get error => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 8); + + @override + String toString() { + return 'PrivateKeyInfo{bitLen: $bitLen, size: $size, error: $error}'; + } +} + +class _PrivateKeyInfoReader extends fb.TableReader { + const _PrivateKeyInfoReader(); + + @override + PrivateKeyInfo createObject(fb.BufferContext bc, int offset) => + PrivateKeyInfo._(bc, offset); +} + +class PrivateKeyInfoBuilder { + PrivateKeyInfoBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addBitLen(int? bitLen) { + fbBuilder.addInt64(0, bitLen); + return fbBuilder.offset; + } + + int addSize(int? size) { + fbBuilder.addInt64(1, size); + return fbBuilder.offset; + } + + int addErrorOffset(int? offset) { + fbBuilder.addOffset(2, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class PrivateKeyInfoObjectBuilder extends fb.ObjectBuilder { + final int? _bitLen; + final int? _size; + final String? _error; + + PrivateKeyInfoObjectBuilder({ + int? bitLen, + int? size, + String? error, + }) : _bitLen = bitLen, + _size = size, + _error = error; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? errorOffset = + _error == null ? null : fbBuilder.writeString(_error!); + fbBuilder.startTable(3); + fbBuilder.addInt64(0, _bitLen); + fbBuilder.addInt64(1, _size); + fbBuilder.addOffset(2, errorOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class PublicKeyInfoResponse { + PublicKeyInfoResponse._(this._bc, this._bcOffset); + factory PublicKeyInfoResponse(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = + _PublicKeyInfoResponseReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + PublicKeyInfo? get output => + PublicKeyInfo.reader.vTableGetNullable(_bc, _bcOffset, 4); + String? get error => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'PublicKeyInfoResponse{output: $output, error: $error}'; + } +} + +class _PublicKeyInfoResponseReader + extends fb.TableReader { + const _PublicKeyInfoResponseReader(); + + @override + PublicKeyInfoResponse createObject(fb.BufferContext bc, int offset) => + PublicKeyInfoResponse._(bc, offset); +} + +class PublicKeyInfoResponseBuilder { + PublicKeyInfoResponseBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addOutputOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int addErrorOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class PublicKeyInfoResponseObjectBuilder extends fb.ObjectBuilder { + final PublicKeyInfoObjectBuilder? _output; + final String? _error; + + PublicKeyInfoResponseObjectBuilder({ + PublicKeyInfoObjectBuilder? output, + String? error, + }) : _output = output, + _error = error; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? outputOffset = _output?.getOrCreateOffset(fbBuilder); + final int? errorOffset = + _error == null ? null : fbBuilder.writeString(_error!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, outputOffset); + fbBuilder.addOffset(1, errorOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class PublicKeyInfo { + PublicKeyInfo._(this._bc, this._bcOffset); + factory PublicKeyInfo(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _PublicKeyInfoReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get bitLen => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 4, 0); + int get size => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 6, 0); + int get e => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 8, 0); + + @override + String toString() { + return 'PublicKeyInfo{bitLen: $bitLen, size: $size, e: $e}'; + } +} + +class _PublicKeyInfoReader extends fb.TableReader { + const _PublicKeyInfoReader(); + + @override + PublicKeyInfo createObject(fb.BufferContext bc, int offset) => + PublicKeyInfo._(bc, offset); +} + +class PublicKeyInfoBuilder { + PublicKeyInfoBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addBitLen(int? bitLen) { + fbBuilder.addInt64(0, bitLen); + return fbBuilder.offset; + } + + int addSize(int? size) { + fbBuilder.addInt64(1, size); + return fbBuilder.offset; + } + + int addE(int? e) { + fbBuilder.addInt64(2, e); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class PublicKeyInfoObjectBuilder extends fb.ObjectBuilder { + final int? _bitLen; + final int? _size; + final int? _e; + + PublicKeyInfoObjectBuilder({ + int? bitLen, + int? size, + int? e, + }) : _bitLen = bitLen, + _size = size, + _e = e; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(3); + fbBuilder.addInt64(0, _bitLen); + fbBuilder.addInt64(1, _size); + fbBuilder.addInt64(2, _e); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/flutter_rsa_ohos/ohos/.gitignore b/flutter_rsa_ohos/ohos/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..fc163ef67c385564e5988662f1b79b35f7c893dd --- /dev/null +++ b/flutter_rsa_ohos/ohos/.gitignore @@ -0,0 +1,10 @@ +/node_modules +/oh_modules +/.preview +/.idea +/build +/.cxx +/.test +/BuildProfile.ets +/oh-package-lock.json5 +local.properties \ No newline at end of file diff --git a/flutter_rsa_ohos/ohos/build-profile.json5 b/flutter_rsa_ohos/ohos/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..37fa510ec59ab79d05a42f8e006c7d1600946623 --- /dev/null +++ b/flutter_rsa_ohos/ohos/build-profile.json5 @@ -0,0 +1,9 @@ +{ + "apiType": "stageMode", + "buildOption": {}, + "targets": [ + { + "name": "default" + } + ] +} diff --git a/flutter_rsa_ohos/ohos/hvigorfile.ts b/flutter_rsa_ohos/ohos/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..056e942ff373c6940f39228036627122e5ec0c2b --- /dev/null +++ b/flutter_rsa_ohos/ohos/hvigorfile.ts @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +export { harTasks } from '@ohos/hvigor-ohos-plugin'; \ No newline at end of file diff --git a/flutter_rsa_ohos/ohos/index.ets b/flutter_rsa_ohos/ohos/index.ets new file mode 100644 index 0000000000000000000000000000000000000000..b499cffb009f0f68ca1fcab015a3119dee9ec811 --- /dev/null +++ b/flutter_rsa_ohos/ohos/index.ets @@ -0,0 +1,17 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import FlutterRsaOhosPlugin from './src/main/ets/components/plugin/FlutterRsaOhosPlugin'; +export default FlutterRsaOhosPlugin; diff --git a/flutter_rsa_ohos/ohos/oh-package.json5 b/flutter_rsa_ohos/ohos/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..eb83218cef6bd34e42d242b3ba82530ea3dd9319 --- /dev/null +++ b/flutter_rsa_ohos/ohos/oh-package.json5 @@ -0,0 +1,12 @@ +{ + "name": "flutter_rsa_ohos", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "index.ets", + "author": "", + "license": "Apache-2.0", + "dependencies": { + "@ohos/crypto-js": "^2.0.4", + "@ohos/flutter_ohos": "file:./har/flutter.har", + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/ohos/src/main/ets/components/plugin/FlutterRsaOhosPlugin.ets b/flutter_rsa_ohos/ohos/src/main/ets/components/plugin/FlutterRsaOhosPlugin.ets new file mode 100644 index 0000000000000000000000000000000000000000..9be7d99a4c7fa6f3e1c74209985c04c92b242ac8 --- /dev/null +++ b/flutter_rsa_ohos/ohos/src/main/ets/components/plugin/FlutterRsaOhosPlugin.ets @@ -0,0 +1,1039 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + FlutterPlugin, + FlutterPluginBinding, + MethodCall, + MethodCallHandler, + MethodChannel, + MethodResult, +} from '@ohos/flutter_ohos'; +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +import CryptoJS from '@ohos/crypto-js'; +import { util } from '@kit.ArkTS'; + +import { StringToUint8Array, Uint8ArrayToHexStr, Uint8ArrayToString, SplitUint8Array, MergeUint8Arrays } from './utils'; + +const TAG = 'fast_rsa::FlutterRsaOhosPlugin'; + +/** FlutterRsaOhosPlugin **/ +export default class FlutterRsaOhosPlugin implements FlutterPlugin, MethodCallHandler { + private channel: MethodChannel | null = null; + private algName: string = 'RSA'; + private nBits: string = '2048'; + private KEY_ALGORITHM: string = ''; + private ivSize: number = 16; + protected cipher: cryptoFramework.Cipher | null = null; + protected random: cryptoFramework.Random = cryptoFramework.createRandom(); + base64Helper: util.Base64Helper = new util.Base64Helper(); + + getUniqueClassName(): string { + return 'FlutterRsaOhosPlugin'; + } + + onAttachedToEngine(binding: FlutterPluginBinding): void { + this.channel = new MethodChannel(binding.getBinaryMessenger(), 'fast_rsa'); + this.channel.setMethodCallHandler(this); + } + + onDetachedFromEngine(binding: FlutterPluginBinding): void { + if (this.channel != null) { + this.channel.setMethodCallHandler(null); + } + } + + async onMethodCall(call: MethodCall, result: MethodResult): Promise { + console.log('fast_rsa:: call.method: ' + call.method); + if (call.method == 'getPlatformVersion') { + result.success('OpenHarmony ^ ^ '); + } else { + switch (call.method) { + case 'encryptOAEP': + await this.encryptOAEP(call, result); + break; + case 'decryptOAEP': + await this.decryptOAEP(call, result); + break; + case 'encryptOAEPBytes': + await this.encryptOAEPBytes(call, result); + break; + case 'decryptOAEPBytes': + await this.decryptOAEPBytes(call, result); + break; + case 'encryptPKCS1v15': + await this.encryptPKCS1v15(call, result); + break; + case 'decryptPKCS1v15': + await this.decryptPKCS1v15(call, result); + break; + case 'encryptPKCS1v15Bytes': + await this.encryptPKCS1v15Bytes(call, result); + break; + case 'decryptPKCS1v15Bytes': + await this.decryptPKCS1v15Bytes(call, result); + break; + case 'convertPrivateKeyToPKCS8': + this.convertPrivateKeyToPKCS8(call, result); + break; + case 'convertPrivateKeyToPKCS1': + this.convertPrivateKeyToPKCS1(call, result); + break; + case 'convertPublicKeyToPKIX': + this.convertPublicKeyToPKIX(call, result); + break; + case 'convertPublicKeyToPKCS1': + this.convertPublicKeyToPKCS1(call, result); + break; + case 'encryptPrivateKey': + await this.encryptPrivateKey(call, result); + break; + case 'decryptPrivateKey': + await this.decryptPrivateKey(call, result); + break; + case 'signPSS': + await this.signPSS(call, result); + break; + case 'verifyPSS': + await this.verifyPSS(call, result); + break; + case 'signPSSBytes': + await this.signPSSBytes(call, result); + break; + case 'verifyPSSBytes': + await this.verifyPSSBytes(call, result); + break; + case 'signPKCS1v15': + await this.signPKCS1v15(call, result); + break; + case 'verifyPKCS1v15': + await this.verifyPKCS1v15(call, result); + break; + case 'signPKCS1v15Bytes': + await this.signPKCS1v15Bytes(call, result); + break; + case 'verifyPKCS1v15Bytes': + await this.verifyPKCS1v15Bytes(call, result); + break; + case 'generate': + this.generate(call, result); + break; + case 'hash': + this.hash(call, result); + break; + case 'base64': + this.base64(call, result); + break; + case 'convertJWKToPrivateKey': + result.error(TAG, 'HarmonyOS not support the convertJWKToPrivateKey API', null); + break; + case 'convertJWKToPublicKey': + result.error(TAG, 'HarmonyOS not support the convertJWKToPublicKey API', null); + break; + case 'convertKeyPairToPKCS12': + result.error(TAG, 'HarmonyOS not support the convertKeyPairToPKCS12 API', null); + break; + case 'convertPrivateKeyToJWK': + result.error(TAG, 'HarmonyOS not support the convertPrivateKeyToJWK API', null); + break; + case 'convertPrivateKeyToPublicKey': + result.error(TAG, 'HarmonyOS not support the convertPrivateKeyToPublicKey API', null); + break; + case 'convertPublicKeyToJWK': + result.error(TAG, 'HarmonyOS not support the convertPublicKeyToJWK API', null); + break; + case 'convertPKCS12ToKeyPair': + result.error(TAG, 'HarmonyOS not support the convertPKCS12ToKeyPair API', null); + break; + default: + result.notImplemented(); + } + } + } + + async signPSS(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: string = call.argument('message'); + let data: Uint8Array = this.getMsgHashArray(hash, StringToUint8Array(message)).data; + let privateKey: string = call.argument('privateKey'); + let saltLength: string = call.argument('saltLength'); + let ohosAlgo: string | null = this.PSSCipherAlgo(hash); + let priKey: cryptoFramework.PriKey = this.getPrivateKeyByPemKeyString(privateKey); + + let signer: cryptoFramework.Sign = this.getSign(ohosAlgo as string); + await signer.init(priKey); + // 在签名初始化后 对PSS参数进行set + let hashLen: number = this.getSaltLen(hash); + if(saltLength.split('.')[1] == 'EQUALS_HASH') { + signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, hashLen); + } else { + let saltLen: number = this.calculateSaltLen(Number(this.nBits), hashLen); + signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, saltLen); + } + await signer.update({ + data + }); + let signMessageBlob: cryptoFramework.DataBlob = await signer.sign(null); + result.success(this.base64Helper.encodeToStringSync(signMessageBlob.data)); + } catch (e) { + console.error(TAG, `signPSSBytes error, ${e.code}, ${e.message}`); + result.error(TAG, `signPSSBytes error, ${e.code}, ${e.message}`, null); + } + } + + async verifyPSS(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: string = call.argument('message'); + let data: Uint8Array = this.getMsgHashArray(hash, StringToUint8Array(message)).data; + let publicKey: string = call.argument('publicKey'); + let saltLength: string = call.argument('saltLength'); + let signature: string = call.argument('signature'); + let signatureData: Uint8Array = this.base64Helper.decodeSync(signature); + let ohosAlgo: string | null = this.PSSCipherAlgo(hash); + let pubKey: cryptoFramework.PubKey = this.getPublicKeyByPemKeyString(publicKey); + + let verifier: cryptoFramework.Verify = this.getVerify(ohosAlgo as string); + // 在验签初始化前 对PSS参数进行set + let hashLen: number = this.getSaltLen(hash); + if(saltLength.split('.')[1] == 'EQUALS_HASH') { + verifier.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, hashLen); + } else { + let saltLen: number = this.calculateSaltLen(Number(this.nBits), hashLen); + verifier.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, saltLen); + } + await verifier.init(pubKey); + await verifier.update({ + data + }); + let verifyResult: boolean = await verifier.verify(null, { + data: signatureData + }); + result.success(verifyResult); + } catch (e) { + console.error(TAG, `verifyPSSBytes error, ${e.code}, ${e.message}`); + result.error(TAG, `verifyPSSBytes error, ${e.code}, ${e.message}`, null); + } + } + + async signPSSBytes(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: Uint8Array = call.argument('message'); + message = this.getMsgHashArray(hash, message).data; + let privateKey: string = call.argument('privateKey'); + let saltLength: string = call.argument('saltLength'); + let ohosAlgo: string | null = this.PSSCipherAlgo(hash); + let priKey: cryptoFramework.PriKey = this.getPrivateKeyByPemKeyString(privateKey); + + let signer: cryptoFramework.Sign = this.getSign(ohosAlgo as string); + await signer.init(priKey); + // 在签名初始化后 对PSS参数进行set + let hashLen: number = this.getSaltLen(hash); + if(saltLength.split('.')[1] == 'EQUALS_HASH') { + signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, hashLen); + } else { + let saltLen: number = this.calculateSaltLen(Number(this.nBits), hashLen); + signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, saltLen); + } + await signer.update({ + data: message + }); + let signMessageBlob: cryptoFramework.DataBlob = await signer.sign(null); + result.success(signMessageBlob.data); + } catch (e) { + console.error(TAG, `signPSSBytes error, ${e.code}, ${e.message}`); + result.error(TAG, `signPSSBytes error, ${e.code}, ${e.message}`, null); + } + } + + async verifyPSSBytes(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: Uint8Array = call.argument('message'); + message = this.getMsgHashArray(hash, message).data; + let publicKey: string = call.argument('publicKey'); + let saltLength: string = call.argument('saltLength'); + let signature: Uint8Array = call.argument('signature'); + let ohosAlgo: string | null = this.PSSCipherAlgo(hash); + let pubKey: cryptoFramework.PubKey = this.getPublicKeyByPemKeyString(publicKey); + + let verifier: cryptoFramework.Verify = this.getVerify(ohosAlgo as string); + // 在验签初始化前 对PSS参数进行set + let hashLen: number = this.getSaltLen(hash); + if(saltLength.split('.')[1] == 'EQUALS_HASH') { + verifier.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, hashLen); + } else { + let saltLen: number = this.calculateSaltLen(Number(this.nBits), hashLen); + verifier.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, saltLen); + } + await verifier.init(pubKey); + await verifier.update({ + data: message + }); + let verifyResult: boolean = await verifier.verify(null, { + data: signature + }); + result.success(verifyResult); + } catch (e) { + console.error(TAG, `verifyPSSBytes error, ${e.code}, ${e.message}`); + result.error(TAG, `verifyPSSBytes error, ${e.code}, ${e.message}`, null); + } + } + + PSSCipherAlgo(hash: string): string { + switch (hash) { + case 'Hash.MD5': + return this.algName + '|PSS|MD5|MGF1_SHA224'; + case 'Hash.SHA1': + return this.algName + '|PSS|SHA1|MGF1_SHA224'; + case 'Hash.SHA224': + return this.algName + '|PSS|SHA224|MGF1_SHA224'; + case 'Hash.SHA256': + return this.algName + '|PSS|SHA256|MGF1_SHA224'; + case 'Hash.SHA384': + return this.algName + '|PSS|SHA384|MGF1_SHA224'; + case 'Hash.SHA512': + return this.algName + '|PSS|SHA512|MGF1_SHA224'; + default: + return this.algName + '|PSS|SHA256|MGF1_SHA224'; + } + } + PKCS1CipherAlgo(hash: string): string { + switch (hash) { + case 'Hash.MD5': + return this.algName + '|PKCS1|MD5'; + case 'Hash.SHA1': + return this.algName + '|PKCS1|SHA1'; + case 'Hash.SHA224': + return this.algName + '|PKCS1|SHA224'; + case 'Hash.SHA256': + return this.algName + '|PKCS1|SHA256'; + case 'Hash.SHA384': + return this.algName + '|PKCS1|SHA384'; + case 'Hash.SHA512': + return this.algName + '|PKCS1|SHA512'; + default: + return this.algName + '|PKCS1|SHA256'; + } + } + + getSaltLen(hash: string): number { + switch (hash) { + case 'Hash.MD5': + return 16; + case 'Hash.SHA1': + return 20; + case 'Hash.SHA224': + return 28; + case 'Hash.SHA256': + return 32; + case 'Hash.SHA384': + return 48; + case 'Hash.SHA512': + return 64; + default: + return 32; + } + } + + /** + * + * @param modulusBitLength RSA算法中的模数n的位数 + * @param hashOutputLength Hash长度 + * @returns saltLength 盐值的长度 + */ + + calculateSaltLen(modulusBitLength: number, hashOutputLength: number): number { + // 计算盐的长度 + const saltLength = Math.ceil((modulusBitLength - 1) / 8) - 2 - hashOutputLength; + + if (saltLength < 0) { + throw new Error("Salt length is too long for the given message."); + } + + return saltLength; + } + + async signPKCS1v15(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: string = call.argument('message'); + let data: Uint8Array = this.getMsgHashArray(hash, StringToUint8Array(message)).data; + let privateKey: string = call.argument('privateKey'); + let ohosAlgo: string | null = this.PSSCipherAlgo(hash); + let priKey: cryptoFramework.PriKey = this.getPrivateKeyByPemKeyString(privateKey); + + let signer: cryptoFramework.Sign = this.getSign(ohosAlgo as string); + await signer.init(priKey); + await signer.update({ + data + }); + let signMessageBlob: cryptoFramework.DataBlob = await signer.sign(null); + result.success(this.base64Helper.encodeToStringSync(signMessageBlob.data)); + } catch (e) { + console.error(TAG, `signPKCS1v15 error, ${e.code}, ${e.message}`); + result.error(TAG, `signPKCS1v15 error, ${e.code}, ${e.message}`, null); + } + } + + async verifyPKCS1v15(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: string = call.argument('message'); + let data: Uint8Array = this.getMsgHashArray(hash, StringToUint8Array(message)).data; + let publicKey: string = call.argument('publicKey'); + let signature: string = call.argument('signature'); + let signatureData: Uint8Array = this.base64Helper.decodeSync(signature); + let ohosAlgo: string | null = this.PSSCipherAlgo(hash); + let pubKey: cryptoFramework.PubKey = this.getPublicKeyByPemKeyString(publicKey); + + let verifier: cryptoFramework.Verify = this.getVerify(ohosAlgo as string); + await verifier.init(pubKey); + await verifier.update({ + data + }); + let verifyResult: boolean = await verifier.verify(null, { + data: signatureData + }); + result.success(verifyResult); + } catch (e) { + console.error(TAG, `verifyPKCS1v15 error, ${e.code}, ${e.message}`); + result.error(TAG, `verifyPKCS1v15 error, ${e.code}, ${e.message}`, null); + } + } + + async signPKCS1v15Bytes(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: Uint8Array = call.argument('message'); + message = this.getMsgHashArray(hash, message).data; + let privateKey: string = call.argument('privateKey'); + let ohosAlgo: string | null = this.PKCS1CipherAlgo(hash); + let priKey: cryptoFramework.PriKey = this.getPrivateKeyByPemKeyString(privateKey); + + let signer: cryptoFramework.Sign = this.getSign(ohosAlgo as string); + await signer.init(priKey); + await signer.update({ + data: message + }); + let signMessageBlob: cryptoFramework.DataBlob = await signer.sign(null); + result.success(signMessageBlob.data); + } catch (e) { + console.error(TAG, `signPKCS1v15Bytes error, ${e.code}, ${e.message}`); + result.error(TAG, `signPKCS1v15Bytes error, ${e.code}, ${e.message}`, null); + } + } + + async verifyPKCS1v15Bytes(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: Uint8Array = call.argument('message'); + message = this.getMsgHashArray(hash, message).data; + let publicKey: string = call.argument('publicKey'); + let signature: Uint8Array = call.argument('signature'); + let ohosAlgo: string | null = this.PKCS1CipherAlgo(hash); + let pubKey: cryptoFramework.PubKey = this.getPublicKeyByPemKeyString(publicKey); + + let verifier: cryptoFramework.Verify = this.getVerify(ohosAlgo as string); + await verifier.init(pubKey); + await verifier.update({ + data: message + }); + let verifyResult: boolean = await verifier.verify(null, { + data: signature + }); + result.success(verifyResult); + } catch (e) { + console.error(TAG, `verifyPKCS1v15Bytes error, ${e.code}, ${e.message}`); + result.error(TAG, `verifyPKCS1v15Bytes error, ${e.code}, ${e.message}`, null); + } + } + + getSign(dartAlgo: string): cryptoFramework.Sign { + return cryptoFramework.createSign(dartAlgo); + } + + getVerify(dartAlgo: string): cryptoFramework.Verify { + return cryptoFramework.createVerify(dartAlgo); + } + + getRSACipher(dartAlgo: string): cryptoFramework.Cipher { + return cryptoFramework.createCipher(dartAlgo); + } + + OAEPCipherAlgo(hash: string): string { + switch (hash) { + case 'Hash.MD5': + return this.algName + '|PKCS1_OAEP|MD5|MGF1_SHA256'; + case 'Hash.SHA1': + return this.algName + '|PKCS1_OAEP|SHA1|MGF1_SHA256'; + case 'Hash.SHA224': + return this.algName + '|PKCS1_OAEP|SHA224|MGF1_SHA256'; + case 'Hash.SHA256': + return this.algName + '|PKCS1_OAEP|SHA256|MGF1_SHA256'; + case 'Hash.SHA384': + return this.algName + '|PKCS1_OAEP|SHA384|MGF1_SHA256'; + case 'Hash.SHA512': + return this.algName + '|PKCS1_OAEP|SHA512|MGF1_SHA256'; + default: + return this.algName + '|PKCS1_OAEP|SHA256|MGF1_SHA256'; + } + } + + async encryptOAEP(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: string = call.argument('message'); + let label: string = call.argument('label'); + let publicKey: string = call.argument('publicKey'); + let ohosAlgo: string | null = this.OAEPCipherAlgo(hash); + let pubKey: cryptoFramework.PubKey = this.getPublicKeyByPemKeyString(publicKey); + let data: Uint8Array = StringToUint8Array(message); + + let cipher: cryptoFramework.Cipher = this.getRSACipher(ohosAlgo as string); + await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); + if(label) { + // RSA加解密PKCS1-OAEP模式填充字节流P + let pSource: Uint8Array = this.getMsgHashArray(hash, StringToUint8Array(label)).data; + cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); + } + const finalRes = await cipher.doFinal({ + data + }); + // 返回加密后的密钥 + result.success(this.base64Helper.encodeToStringSync(finalRes.data)); + } catch (e) { + console.error(TAG, `encryptOAEP error, ${e.code}, ${e.message}`); + result.error(TAG, `encryptOAEP error, ${e.code}, ${e.message}`, null); + } + } + + async decryptOAEP(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let ciphertext: string = call.argument('ciphertext'); + let label: string = call.argument('label'); + let privateKey: string = call.argument('privateKey'); + let ohosAlgo: string | null = this.OAEPCipherAlgo(hash); + let encrypted: Uint8Array = this.base64Helper.decodeSync(ciphertext); + let priKey: cryptoFramework.PriKey = this.getPrivateKeyByPemKeyString(privateKey); + + let cipher: cryptoFramework.Cipher = this.getRSACipher(ohosAlgo as string); + if(label) { + // RSA加解密PKCS1-OAEP模式填充字节流P + let pSource: Uint8Array = this.getMsgHashArray(hash, StringToUint8Array(label)).data; + cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); + } + await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, priKey, null); + const finalRes = await cipher.doFinal({ + data: encrypted + }); + result.success(Uint8ArrayToString(finalRes.data)); + } catch (e) { + console.error(TAG, `decryptOAEP error, ${e.code}, ${e.message}`); + result.error(TAG, `decryptOAEP error, ${e.code}, ${e.message}`, null); + } + } + + async encryptOAEPBytes(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let message: Uint8Array = call.argument('message'); + let label: string = call.argument('label'); + let publicKey: string = call.argument('publicKey'); + let ohosAlgo: string | null = this.OAEPCipherAlgo(hash); + let pubKey: cryptoFramework.PubKey = this.getPublicKeyByPemKeyString(publicKey); + + let cipher: cryptoFramework.Cipher = this.getRSACipher(ohosAlgo as string); + await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); + if(label) { + // RSA加解密PKCS1-OAEP模式填充字节流P + let pSource: Uint8Array = this.getMsgHashArray(hash, StringToUint8Array(label)).data; + cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); + } + const finalRes = await cipher.doFinal({ + data: message + }); + // 返回加密后的密钥 + result.success(finalRes.data); + } catch (e) { + console.error(TAG, `encryptOAEPBytes error, ${e.code}, ${e.message}`); + result.error(TAG, `encryptOAEPBytes error, ${e.code}, ${e.message}`, null); + } + } + + async decryptOAEPBytes(call: MethodCall, result: MethodResult) { + try { + let hash: string = call.argument('hash'); + let ciphertext: Uint8Array = call.argument('ciphertext'); + let label: string = call.argument('label'); + let privateKey: string = call.argument('privateKey'); + let ohosAlgo: string | null = this.OAEPCipherAlgo(hash); + let priKey: cryptoFramework.PriKey = this.getPrivateKeyByPemKeyString(privateKey); + + let cipher: cryptoFramework.Cipher = this.getRSACipher(ohosAlgo as string); + if(label) { + // RSA加解密PKCS1-OAEP模式填充字节流P + let pSource: Uint8Array = this.getMsgHashArray(hash, StringToUint8Array(label)).data; + cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); + } + await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, priKey, null); + const finalRes = await cipher.doFinal({ + data: ciphertext + }); + result.success(finalRes.data); + } catch (e) { + console.error(TAG, `decryptOAEPBytes error, ${e.code}, ${e.message}`); + result.error(TAG, `decryptOAEPBytes error, ${e.code}, ${e.message}`, null); + } + } + + async encryptPKCS1v15(call: MethodCall, result: MethodResult) { + try { + let message: string = call.argument('message'); + let publicKey: string = call.argument('publicKey'); + let ohosAlgo: string = this.algName + '|PKCS1'; + let pubKey: cryptoFramework.PubKey = this.getPublicKeyByPemKeyString(publicKey); + let data: Uint8Array = StringToUint8Array(message); + + let cipher: cryptoFramework.Cipher = this.getRSACipher(ohosAlgo); + await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); + const finalRes = await cipher.doFinal({ + data + }); + // 返回加密后的密钥 + result.success(this.base64Helper.encodeToStringSync(finalRes.data)); + } catch (e) { + console.error(TAG, `encryptPKCS1v15 error, ${e.code}, ${e.message}`); + result.error(TAG, `encryptPKCS1v15 error, ${e.code}, ${e.message}`, null); + } + } + + async decryptPKCS1v15(call: MethodCall, result: MethodResult) { + try { + let ciphertext: string = call.argument('ciphertext'); + let privateKey: string = call.argument('privateKey'); + let ohosAlgo: string = this.algName + '|PKCS1'; + let encrypted: Uint8Array = this.base64Helper.decodeSync(ciphertext); + let priKey: cryptoFramework.PriKey = this.getPrivateKeyByPemKeyString(privateKey); + + let cipher: cryptoFramework.Cipher = this.getRSACipher(ohosAlgo); + await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, priKey, null); + const finalRes = await cipher.doFinal({ + data: encrypted + }); + result.success(Uint8ArrayToString(finalRes.data)); + } catch (e) { + console.error(TAG, `decryptPKCS1v15 error, ${e.code}, ${e.message}`); + result.error(TAG, `decryptPKCS1v15 error, ${e.code}, ${e.message}`, null); + } + } + + async encryptPKCS1v15Bytes(call: MethodCall, result: MethodResult) { + try { + let message: Uint8Array = call.argument('message'); + let publicKey: string = call.argument('publicKey'); + let ohosAlgo: string = this.algName + '|PKCS1'; + let pubKey: cryptoFramework.PubKey = this.getPublicKeyByPemKeyString(publicKey); + + let cipher: cryptoFramework.Cipher = this.getRSACipher(ohosAlgo); + await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); + const finalRes = await cipher.doFinal({ + data: message + }); + // 返回加密后的密钥 + result.success(finalRes.data); + } catch (e) { + console.error(TAG, `encryptPKCS1v15Bytes error, ${e.code}, ${e.message}`); + result.error(TAG, `encryptPKCS1v15Bytes error, ${e.code}, ${e.message}`, null); + } + } + + async decryptPKCS1v15Bytes(call: MethodCall, result: MethodResult) { + try { + let ciphertext: Uint8Array = call.argument('ciphertext'); + let privateKey: string = call.argument('privateKey'); + let ohosAlgo: string = this.algName + '|PKCS1'; + let priKey: cryptoFramework.PriKey = this.getPrivateKeyByPemKeyString(privateKey); + + let cipher: cryptoFramework.Cipher = this.getRSACipher(ohosAlgo); + await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, priKey, null); + const finalRes = await cipher.doFinal({ + data: ciphertext + }); + result.success(finalRes.data); + } catch (e) { + console.error(TAG, `decryptPKCS1v15Bytes error, ${e.code}, ${e.message}`); + result.error(TAG, `decryptPKCS1v15Bytes error, ${e.code}, ${e.message}`, null); + } + } + + convertPrivateKeyToPKCS8(call: MethodCall, result: MethodResult) { + try { + let privateKey: string = call.argument('privateKey'); + let rsaGenerator = cryptoFramework.createAsyKeyGenerator(this.algName); + let keyPair: cryptoFramework.KeyPair = rsaGenerator.convertPemKeySync(null, privateKey); + let priKey: string = keyPair.priKey.getEncodedPem('PKCS8'); + result.success(priKey); + } catch (e) { + console.error(TAG, `convertPrivateKeyToPKCS8 error, ${e.code}, ${e.message}`); + result.error(TAG, `convertPrivateKeyToPKCS8 error, ${e.code}, ${e.message}`, null); + } + } + + convertPrivateKeyToPKCS1(call: MethodCall, result: MethodResult) { + try { + let privateKey: string = call.argument('privateKey'); + let rsaGenerator = cryptoFramework.createAsyKeyGenerator(this.algName); + let keyPair: cryptoFramework.KeyPair = rsaGenerator.convertPemKeySync(null, privateKey); + let priKey: string = keyPair.priKey.getEncodedPem('PKCS1'); + result.success(priKey); + } catch (e) { + console.error(TAG, `convertPrivateKeyToPKCS1 error, ${e.code}, ${e.message}`); + result.error(TAG, `convertPrivateKeyToPKCS1 error, ${e.code}, ${e.message}`, null); + } + } + + convertPublicKeyToPKIX(call: MethodCall, result: MethodResult) { + try { + let publicKey: string = call.argument('publicKey'); + let rsaGenerator = cryptoFramework.createAsyKeyGenerator(this.algName); + let keyPair: cryptoFramework.KeyPair = rsaGenerator.convertPemKeySync(publicKey, null); + let pubKey: string = keyPair.pubKey.getEncodedPem('X509'); + result.success(pubKey); + } catch (e) { + console.error(TAG, `convertPublicKeyToPKIX error, ${e.code}, ${e.message}`); + result.error(TAG, `convertPublicKeyToPKIX error, ${e.code}, ${e.message}`, null); + } + } + + convertPublicKeyToPKCS1(call: MethodCall, result: MethodResult) { + try { + let publicKey: string = call.argument('publicKey'); + let rsaGenerator = cryptoFramework.createAsyKeyGenerator(this.algName); + let keyPair: cryptoFramework.KeyPair = rsaGenerator.convertPemKeySync(publicKey, null); + let pubKey: string = keyPair.pubKey.getEncodedPem('PKCS1'); + result.success(pubKey); + } catch (e) { + console.error(TAG, `convertPublicKeyToPKCS1 error, ${e.code}, ${e.message}`); + result.error(TAG, `convertPublicKeyToPKCS1 error, ${e.code}, ${e.message}`, null); + } + } + + async encryptPrivateKey(call: MethodCall, result: MethodResult) { + try { + let privateKey: string = call.argument('privateKey'); + let password: string = call.argument('password'); + this.KEY_ALGORITHM = call.argument('cipher').split('.')[1]; + if(this.KEY_ALGORITHM.indexOf('DES') !== -1) { + let res: string = this.callDESEncrypt(privateKey, password, this.KEY_ALGORITHM); + result.success(res); + } else { + // AES加解密 + let res: string = await this.callAESEncrypt(privateKey, password, this.KEY_ALGORITHM); + result.success(res); + } + } catch (e) { + console.error(TAG, `encryptPrivateKey error, ${e.code}, ${e.message}`); + result.error(TAG, `encryptPrivateKey error, ${e.code}, ${e.message}`, null); + } + } + + async decryptPrivateKey(call: MethodCall, result: MethodResult) { + try { + let privateKeyEncrypted: string = call.argument('privateKeyEncrypted'); + let password: string = call.argument('password'); + if(this.KEY_ALGORITHM.indexOf('DES') !== -1) { + let res: string = this.callDESDecrypt(privateKeyEncrypted, password, this.KEY_ALGORITHM); + result.success(res); + } else { + // AES加解密 + let res: string = await this.callAESDecrypt(privateKeyEncrypted, password, this.KEY_ALGORITHM); + result.success(res); + } + } catch (e) { + console.error(TAG, `decryptPrivateKey error, ${e.code}, ${e.message}`); + result.error(TAG, `decryptPrivateKey error, ${e.code}, ${e.message}`, null); + } + } + + callDESEncrypt(privatePemKey: string, password: string, cipher: string): string { + let result: string = ''; + try { + let result: string; + // pem格式字符串转为Uint8Array格式的私钥 + let keyArr: Uint8Array = this.getPrivateKeyByPemKeyString(privatePemKey).getEncoded().data; + // Uint8Array格式的私钥转为base64加密的字符串 + let clearText: string = this.base64Helper.encodeToStringSync(keyArr); + let newKey: CryptoJS.lib.WordArray = CryptoJS.enc.Utf8.parse(password); + // base64加密的字符串在通过DES加密返回加密后的字符串 + if(cipher == 'DES') { + result = CryptoJS.DES.encrypt(clearText, newKey,{ + iv:CryptoJS.enc.Utf8.parse(''), + mode: CryptoJS.mode.CBC, + padding: CryptoJS.pad.Pkcs7 + }).toString(); + } else { + result = CryptoJS.TripleDES.encrypt(clearText, newKey,{ + iv:CryptoJS.enc.Utf8.parse(''), + mode: CryptoJS.mode.CBC, + padding: CryptoJS.pad.Pkcs7 + }).toString(); + } + return result; + } catch (e) { + console.error(TAG, `callDESEncrypt error, ${e.code}, ${e.message}`); + return result; + } + } + + callDESDecrypt(privateKeyEncrypted: string, password: string, cipher: string): string { + let result: string = ''; + try { + let result: string; + let newKey: CryptoJS.lib.WordArray = CryptoJS.enc.Utf8.parse(password); + if(cipher == 'DES') { + // DES加密后的字符串通过DES解密返回 base64加密的字符串 + result = CryptoJS.DES.decrypt(privateKeyEncrypted, newKey,{ + iv:CryptoJS.enc.Utf8.parse(''), + mode: CryptoJS.mode.CBC, + padding: CryptoJS.pad.Pkcs7 + }).toString(CryptoJS.enc.Utf8); + } else { + result = CryptoJS.TripleDES.decrypt(privateKeyEncrypted, newKey,{ + iv:CryptoJS.enc.Utf8.parse(''), + mode: CryptoJS.mode.CBC, + padding: CryptoJS.pad.Pkcs7 + }).toString(CryptoJS.enc.Utf8); + } + // base64解密后返回 Uint8Array格式的私钥 + let keyArr: Uint8Array = this.base64Helper.decodeSync(result); + // Uint8Array格式的私钥转为PEM格式的密钥字符串 + result = this.getPrivateKeyByUint8Array(keyArr); + return result; + } catch (e) { + console.error(TAG, `callDESDecrypt error, ${e.code}, ${e.message}`); + return result; + } + } + + async callAESEncrypt(privatePemKey: string, password: string, cipher: string): Promise { + let result: string = ''; + try { + // pem格式字符串转为Uint8Array格式的私钥 + let plainText: Uint8Array = this.getPrivateKeyByPemKeyString(privatePemKey).getEncoded().data; + let keySize: number = this.getKeySize(cipher); + cipher = cipher + '|CBC|PKCS7'; + let ivParameterSpec: cryptoFramework.IvParamsSpec = this.getParameterSpec(); + // 使用PBKDF2派生密钥 + let deriveKey: cryptoFramework.DataBlob = this.kdfSync(password, SplitUint8Array(ivParameterSpec.iv.data, 0, 8), keySize); + let symKey: cryptoFramework.SymKey = this.convertDeriveKeyByData(deriveKey); + + let cipherInstance = cryptoFramework.createCipher(cipher); + await cipherInstance.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ivParameterSpec); + let cipherData = await cipherInstance.doFinal({ + data: plainText + }); + // iv向量和Uint8Array格式的私钥进行合并返回 + let combined = MergeUint8Arrays(ivParameterSpec.iv.data, cipherData.data); + // Uint8Array格式的私钥转为base64加密的字符串 + result = this.base64Helper.encodeToStringSync(combined); + return result; + } catch (e) { + console.error(TAG, `callAESEncrypt error, ${e.code}, ${e.message}`); + return result; + } + } + + async callAESDecrypt(privateKeyEncrypted: string, password: string, cipher: string): Promise { + let result: string = ''; + try { + let cipherText: Uint8Array = this.base64Helper.decodeSync(privateKeyEncrypted); + let keySize: number = this.getKeySize(cipher); + cipher = cipher + '|CBC|PKCS7'; + let ivParameterSpec: cryptoFramework.IvParamsSpec = this.getParameterSpec(); + // 提取密文中的iv + let ivBlob: cryptoFramework.DataBlob = { data: SplitUint8Array(cipherText, 0, this.ivSize)}; + ivParameterSpec.iv = ivBlob; + let cipherData: Uint8Array = SplitUint8Array(cipherText, this.ivSize, cipherText.length); + // 使用加密时的配置参数进行PBKDF2算法派生密钥 + let deriveKey: cryptoFramework.DataBlob = this.kdfSync(password, SplitUint8Array(ivParameterSpec.iv.data, 0, 8), keySize); + let symKey: cryptoFramework.SymKey = this.convertDeriveKeyByData(deriveKey); + + let cipherInstance = cryptoFramework.createCipher(cipher); + await cipherInstance.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, ivParameterSpec); + let decryptData = await cipherInstance.doFinal({ + data: cipherData + }); + // Uint8Array格式的私钥转为PEM格式的密钥字符串 + result = this.getPrivateKeyByUint8Array(decryptData.data); + return result; + } catch (e) { + console.error(TAG, `callAESDecrypt error, ${e.code}, ${e.message}`); + return result; + } + } + + getKeySize (cipher: string): number { + let keySize: number; + + if (cipher.includes('256')) { + keySize = 32; + } else if (cipher.includes('192')) { + keySize = 24; + } else { + keySize = 16; + } + return keySize; + } + + // PBKDF2密钥派生 keySize: AES128/16字节 AES192/24字节 AES256/32字节 + kdfSync(password: string, salt: Uint8Array, keySize: number): cryptoFramework.DataBlob { + let spec: cryptoFramework.PBKDF2Spec = { + algName: 'PBKDF2', + password, + salt, + iterations: 10000, + keySize + }; + let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); + let secret: cryptoFramework.DataBlob = kdf.generateSecretSync(spec); + return secret; + } + + convertDeriveKeyByData(keyData: cryptoFramework.DataBlob): cryptoFramework.SymKey { + let aesGenerator = cryptoFramework.createSymKeyGenerator(this.KEY_ALGORITHM); + let symKey: cryptoFramework.SymKey = aesGenerator.convertKeySync(keyData); + return symKey; + } + + getParameterSpec(): cryptoFramework.IvParamsSpec { + let ivBlob: cryptoFramework.DataBlob = this.getIvBlob(); + let ivParamsSpec: cryptoFramework.IvParamsSpec = { + algName: "IvParamsSpec", + iv: ivBlob + }; + return ivParamsSpec; + } + + getIvBlob(): cryptoFramework.DataBlob { + return this.random.generateRandomSync(this.ivSize); + } + + getPrivateKeyByUint8Array(keyArr: Uint8Array): string { + let priKey: string; + let rsaGenerator = cryptoFramework.createAsyKeyGenerator(this.algName); + let keyPair: cryptoFramework.KeyPair = rsaGenerator.convertKeySync(null, { + data: keyArr + }); + priKey = keyPair.priKey.getEncodedPem('PKCS1'); + return priKey; + } + + getPrivateKeyByPemKeyString(priPemKeyString: string): cryptoFramework.PriKey { + let priKey: cryptoFramework.PriKey; + let rsaGenerator = cryptoFramework.createAsyKeyGenerator(this.algName); + let keyPair: cryptoFramework.KeyPair = rsaGenerator.convertPemKeySync(null, priPemKeyString); + priKey = keyPair.priKey; + return priKey; + } + + getPublicKeyByPemKeyString(pubPemKeyString: string): cryptoFramework.PubKey { + let pubKey: cryptoFramework.PubKey; + let rsaGenerator = cryptoFramework.createAsyKeyGenerator(this.algName); + let keyPair: cryptoFramework.KeyPair = rsaGenerator.convertPemKeySync(pubPemKeyString, null); + pubKey = keyPair.pubKey; + return pubKey; + } + + generate(call: MethodCall, result: MethodResult) { + try { + this.nBits = call.argument('nBits'); + let keyPair: cryptoFramework.KeyPair = this.getAsyKey(); + let publicKey: string = keyPair.pubKey.getEncodedPem('X509'); + let privateKey: string = keyPair.priKey.getEncodedPem('PKCS1'); + let map: Map = new Map(); + map.set('publicKey', publicKey); + map.set('privateKey', privateKey); + result.success(map); + } catch (e) { + console.error(TAG, `generate error, ${e.code}, ${e.message}`); + result.error(TAG, `generate error, ${e.code}, ${e.message}`, null); + } + } + + getAsyKey(): cryptoFramework.KeyPair { + let keyPair: cryptoFramework.KeyPair; + if(this.algName.length > 3) { + this.algName = 'RSA'; + } + this.algName = this.nBits ? this.algName + this.nBits : this.algName + '2048'; + let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(this.algName); + keyPair = asyKeyGenerator.generateKeyPairSync(); + return keyPair; + } + + switchHashCipherAlgo(dartAlgo: string): string { + switch (dartAlgo) { + case 'Hash.MD5': + return 'MD5'; + case 'Hash.SHA1': + return 'SHA1'; + case 'Hash.SHA224': + return 'SHA224'; + case 'Hash.SHA256': + return 'SHA256'; + case 'Hash.SHA384': + return 'SHA384'; + case 'Hash.SHA512': + return 'SHA512'; + default: + return 'SHA256'; + } + } + + getMsgHashArray(hash: string, message: Uint8Array): cryptoFramework.DataBlob { + hash = this.switchHashCipherAlgo(hash); + let md = cryptoFramework.createMd(hash); + md.updateSync({ data: message}); + return md.digestSync(); + } + + hash(call: MethodCall, result: MethodResult) { + try { + let message: string = call.argument('message'); + let hash: string = call.argument('hash'); + let mdResult: cryptoFramework.DataBlob = this.getMsgHashArray(hash, StringToUint8Array(message)); + let data: string = Uint8ArrayToHexStr(mdResult.data); + result.success(data); + } catch (e) { + console.error(TAG, `hash error, ${e.code}, ${e.message}`); + result.error(TAG, `hash error, ${e.code}, ${e.message}`, null); + } + } + + base64(call: MethodCall, result: MethodResult) { + try { + let message: string = call.argument('message'); + let data: string = this.base64Helper.encodeToStringSync(StringToUint8Array(message)); + result.success(data); + } catch (e) { + console.error(TAG, `base64 error, ${e.code}, ${e.message}`); + result.error(TAG, `base64 error, ${e.code}, ${e.message}`, null); + } + } +} \ No newline at end of file diff --git a/flutter_rsa_ohos/ohos/src/main/ets/components/plugin/utils/index.ts b/flutter_rsa_ohos/ohos/src/main/ets/components/plugin/utils/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ee7195c4541864e57af5e55501c2395287989f7 --- /dev/null +++ b/flutter_rsa_ohos/ohos/src/main/ets/components/plugin/utils/index.ts @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { util, buffer } from '@kit.ArkTS'; + +export function StringToUint8Array(str: string): Uint8Array { + let textEncoder = new util.TextEncoder('utf-8'); + let result = textEncoder.encodeInto(str); + return result; +} + +export function Uint8ArrayToString(fileData: Uint8Array): string { + let dataString = ''; + let textDecoder = util.TextDecoder.create('utf-8'); + dataString = textDecoder.decodeWithStream(fileData); + return dataString; +} + +// 遍历对象返回map +export function ConvertObjectToMap(obj: Object): Map { + let map = new Map(); + + for (let key in obj) { + if (obj.hasOwnProperty(key)) { + map.set(key, obj[key]); + } + } + + return map; +} + +export function MergeUint8Arrays(arr1: Uint8Array, arr2: Uint8Array): Uint8Array { + return Uint8Array.from([...arr1, ...arr2]); +} + +export function SplitUint8Array(array: Uint8Array, start: number, end: number): Uint8Array { + if (start < 0 || end > array.length || start > end) { + throw new Error('Invalid start or end index'); + } + + // 创建一个新的 Uint8Array,包含从 start 到 end 的元素 + const splitArray = new Uint8Array(end - start); + splitArray.set(array.slice(start, end)); + + return splitArray; +} + +export function BigIntToArray(bigIntValue: string | number | bigint): Uint8Array { + // 将BigInt转换为字符串 + const stringValue = bigIntValue.toString(); + + // 将字符串转换为Uint8Array + return StringToUint8Array(stringValue); +} + +//Uint8Array转十六进制 +export function Uint8ArrayToHexStr(data: Uint8Array): string { + return buffer.from(data).toString('hex'); +} + +//十六进制转Uint8Array +export function HexStrToUint8Array(data: string): Uint8Array { + return new Uint8Array(buffer.from(data, 'hex').buffer); +} \ No newline at end of file diff --git a/flutter_rsa_ohos/ohos/src/main/module.json5 b/flutter_rsa_ohos/ohos/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..af1d44357836588d60b682e83df4db64181d0da9 --- /dev/null +++ b/flutter_rsa_ohos/ohos/src/main/module.json5 @@ -0,0 +1,10 @@ +{ + "module": { + "name": "flutter_rsa_ohos", + "type": "har", + "deviceTypes": [ + "default", + "tablet" + ] + } +} diff --git a/flutter_rsa_ohos/pubspec.yaml b/flutter_rsa_ohos/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7b99240147899d107431987688cd78c5ee876c0 --- /dev/null +++ b/flutter_rsa_ohos/pubspec.yaml @@ -0,0 +1,74 @@ +name: flutter_rsa_ohos +description: library for use RSA with support for ohos. +version: 1.0.0 +repository: https://gitee.com/openharmony-sig/fluttertpc_fast-rsa + +environment: + sdk: '>=2.19.6 <3.0.0' + flutter: ">=2.5.0" + +dependencies: + flutter: + sdk: flutter + flutter_web_plugins: + sdk: flutter + ffi: ^2.0.1 + flat_buffers: ^2.0.5 + path: ^1.8.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + # This section identifies this Flutter project as a plugin project. + # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.) + # which should be registered in the plugin registry. This is required for + # using method channels. + # The Android 'package' specifies package in which the registered class is. + # This is required for using method channels on Android. + # The 'ffiPlugin' specifies that native code should be built and bundled. + # This is required for using `dart:ffi`. + # All these are used by the tooling to maintain consistency when + # adding or updating assets for this project. + plugin: + platforms: + ohos: + package: com.example.flutter_rsa_ohos + pluginClass: FlutterRsaOhosPlugin + + # To add assets to your plugin package, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + # + # For details regarding assets in packages, see + # https://flutter.dev/assets-and-images/#from-packages + # + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # To add custom fonts to your plugin package, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts in packages, see + # https://flutter.dev/custom-fonts/#from-packages