├── .editorconfig ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── webauthn ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src ├── androidTest ├── AndroidManifest.xml └── java │ └── jp │ └── co │ └── lycorp │ └── webauthn │ ├── AuthenticatorTest.kt │ ├── authenticator │ ├── keygenerator │ │ └── Fido2KeyGeneratorTest.kt │ └── objectgenerator │ │ └── Fido2ObjectGeneratorTest.kt │ └── util │ ├── MockCredentialSourceStorage.kt │ └── TestFragmentActivity.kt ├── main ├── AndroidManifest.xml └── java │ └── jp │ └── co │ └── lycorp │ └── webauthn │ ├── authenticator │ ├── Authenticator.kt │ ├── AuthenticatorProvider.kt │ ├── keygenerator │ │ ├── BiometricKeyGenerator.kt │ │ ├── DeviceCredentialKeyGenerator.kt │ │ └── Fido2KeyGenerator.kt │ └── objectgenerator │ │ ├── AndroidKeyObjectGenerator.kt │ │ ├── Fido2ObjectGenerator.kt │ │ └── NoneObjectGenerator.kt │ ├── db │ └── CredentialSourceStorage.kt │ ├── exceptions │ └── WebAuthnException.kt │ ├── handler │ ├── AuthenticationHandler.kt │ ├── BiometricAuthenticationHandler.kt │ ├── DeviceCredentialAuthenticationHandler.kt │ └── KeyguardManagerWrapper.kt │ ├── model │ ├── AssertionObject.kt │ ├── AttestationConveyancePreference.kt │ ├── AttestationObject.kt │ ├── AttestationStatement.kt │ ├── AuthenticationExtensions.kt │ ├── AuthenticationMethod.kt │ ├── AuthenticatorAttachment.kt │ ├── AuthenticatorData.kt │ ├── AuthenticatorGetAssertionResult.kt │ ├── AuthenticatorMakeCredentialResult.kt │ ├── AuthenticatorResponse.kt │ ├── AuthenticatorSelectionCriteria.kt │ ├── AuthenticatorTransport.kt │ ├── AuthenticatorType.kt │ ├── CborSerializable.kt │ ├── CollectedClientData.kt │ ├── CredentialProtection.kt │ ├── Fido2PromptInfo.kt │ ├── Fido2UserAuthResult.kt │ ├── PublicKeyCredentialCreationOptions.kt │ ├── PublicKeyCredentialDescriptor.kt │ ├── PublicKeyCredentialParams.kt │ ├── PublicKeyCredentialRequestOptions.kt │ ├── PublicKeyCredentialResult.kt │ ├── PublicKeyCredentialRpEntity.kt │ ├── PublicKeyCredentialSource.kt │ ├── PublicKeyCredentialType.kt │ └── PublicKeyCredentialUserEntity.kt │ ├── publickeycredential │ └── PublicKeyCredential.kt │ ├── rp │ └── RelyingParty.kt │ └── util │ ├── Constants.kt │ ├── Encoding.kt │ ├── Fido2Util.kt │ └── SecureExecutionHelper.kt └── test └── java └── jp └── co └── lycorp └── webauthn ├── AuthenticatorTest.kt ├── PublicKeyCredentialTest.kt └── util └── MockCredentialSourceStorage.kt /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 4 7 | indent_style = space 8 | insert_final_newline = true 9 | max_line_length = 120 10 | tab_width = 4 11 | trim_trailing_whitespace = true 12 | ij_continuation_indent_size = 8 13 | ij_smart_tabs = false 14 | 15 | [{*.kt,*.kts}] 16 | # https://pinterest.github.io/ktlint/rules/configuration-ktlint/ 17 | 18 | ktlint_code_style = android_studio 19 | 20 | #ktlint_standard = disabled # Disable all rulesg from the `standard` rule set provided by KtLint 21 | 22 | # Enable the rules from the `standard` rule set provided by KtLint 23 | 24 | # Disable the rules from the 'standard' rule set provided by KtLint 25 | ktlint_standard_discouraged-comment-location = disabled 26 | ktlint_standard_comment-wrapping = disabled 27 | ktlint_standard_property-naming = disabled 28 | ktlint_standard_class-naming = disabled 29 | 30 | # trailing_comma rules still have issue. 31 | # https://github.com/pinterest/ktlint/issues/1557 32 | ktlint_standard_trailing-comma-on-call-site = disabled 33 | ktlint_standard_trailing-comma-on-declaration-site = disabled 34 | # https://github.com/pinterest/ktlint/issues/1733 35 | ktlint_standard_no-semi = disabled 36 | 37 | ## `Set from...` on the right -> (`Predefined style`) -> `Kotlin style guide` (Kotlin plugin 1.2.20+). 38 | ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL 39 | 40 | ## open `Code Generation` tab 41 | # uncheck `Line comment at first column`; 42 | ij_kotlin_line_comment_at_first_column = false 43 | # select `Add a space at comment start` 44 | ij_kotlin_line_comment_add_space = true 45 | 46 | ## open `Compose` tab 47 | # select `Enable Compose formatting for Modifiers` 48 | ij_kotlin_use_custom_formatting_for_modifiers = true 49 | 50 | ## open `Imports tab` 51 | # select `Use single name import` (all of them); 52 | ij_kotlin_name_count_to_use_star_import = 2147483647 53 | ij_kotlin_name_count_to_use_star_import_for_members = 2147483647 54 | 55 | ## open `Wrapping and Braces` tab 56 | # change `Keep Maximum Blank Lines` / `In declarations` & `In code` to 1 57 | ij_kotlin_keep_blank_lines_in_declarations = 1 58 | ij_kotlin_keep_blank_lines_in_code = 1 59 | # and `Before '}'` to 0 60 | ij_kotlin_keep_blank_lines_before_right_brace = 0 61 | 62 | ## open `Wrapping and Braces` tab 63 | # uncheck `Function declaration parameters` / `Align when multiline`. 64 | ij_kotlin_align_multiline_parameters = false 65 | 66 | ## open `Tabs and Indents` tab 67 | # change `Continuation indent` to the same value as `Indent` (4 by default) 68 | continuation_indent_size = 4 69 | ij_continuation_indent_size = 4 70 | 71 | # Other: Insert imports for nested classes -> false 72 | ij_kotlin_import_nested_classes = false 73 | # Import Layout: import all other imports, then import all alias imports 74 | ij_kotlin_imports_layout = *,^ 75 | 76 | # When these values are set any values, disabled trailing_comma rules are activated 77 | #ij_kotlin_allow_trailing_comma = false 78 | #ij_kotlin_allow_trailing_comma_on_call_site = false 79 | 80 | # For Jetpack Compose & Tests 81 | ktlint_function_naming_ignore_when_annotated_with=Composable, Test 82 | 83 | [{*.xsl,*.xsd,*.xml}] 84 | ij_continuation_indent_size = 4 85 | ij_xml_use_custom_settings = true 86 | ij_xml_block_comment_at_first_column = true 87 | ij_xml_keep_indents_on_empty_lines = false 88 | ij_xml_line_comment_at_first_column = true 89 | 90 | [{*.yml,*.yaml}] 91 | indent_size = 2 92 | ij_yaml_keep_indents_on_empty_lines = false 93 | ij_yaml_keep_line_breaks = true 94 | 95 | [{*.md,*.markdown}] 96 | max_line_length = 99999 97 | trim_trailing_whitespace = false 98 | 99 | [*.json] 100 | indent_size = 2 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | local.properties 11 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual 10 | identity and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the overall 26 | community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or advances of 31 | any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email address, 35 | without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official email address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | [INSERT CONTACT METHOD]. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series of 86 | actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or permanent 93 | ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within the 113 | community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.1, available at 119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 123 | 124 | For answers to common questions about this code of conduct, see the FAQ at 125 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 126 | [https://www.contributor-covenant.org/translations][translations]. 127 | 128 | [homepage]: https://www.contributor-covenant.org 129 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 130 | [Mozilla CoC]: https://github.com/mozilla/diversity 131 | [FAQ]: https://www.contributor-covenant.org/faq 132 | [translations]: https://www.contributor-covenant.org/translations 133 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute to WebAuthn Kotlin 2 | 3 | First of all, thank you so much for taking your time to contribute! 4 | WebAuthn Kotlin is not very different from any other open source projects. 5 | It will be fantastic if you help us by doing any of the following: 6 | 7 | - File an issue in [the issue tracker](https://github.com/line/webauthn-kotlin/issues) 8 | to report bugs and propose new features and improvements. 9 | - Ask a question using [the issue tracker](https://github.com/line/webauthn-kotlin/issues). 10 | - Contribute your work by sending [a pull request](https://github.com/line/webauthn-kotlin/pulls). 11 | 12 | ## Contributor license agreement 13 | 14 | When you are sending a pull request and it's a non-trivial change beyond fixing 15 | typos, please sign [the ICLA (individual contributor license agreement)](https://cla-assistant.io/line/webauthn-kotlin). 16 | Please [contact us](mailto:dl_oss_dev@linecorp.com) if you need the CCLA 17 | (corporate contributor license agreement). 18 | 19 | ## Code of conduct 20 | 21 | We expect contributors to follow [our code of conduct](./CODE_OF_CONDUCT.md). 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebAuthn Kotlin 2 | 3 | WebAuthn Kotlin is an open source toolkit for secure, password-less authentication in mobile apps. Developed in Kotlin, it integrates seamlessly with native Android apps and adheres to WebAuthn 2.0 standards, boosting security and user experience. 4 | 5 | Designed to align with modern Android development, the SDK offers easy integration and customization. It equips developers with tools for advanced authentication, such as device credentials and biometrics, simplifying logins and enhancing security. 6 | 7 | 8 | ## Components 9 | 10 | ### PublicKeyCredential 11 | The `PublicKeyCredential` serves as the client within the authentication framework, interacting with the authenticator to carry out the authentication process and communicating with the relying party. It supports two primary operations for secure, password-less authentication: 12 | 13 | - **create()**: Starts the process of generating new asymmetric key credentials via an authenticator. 14 | - **get()**: Prompts the user to authenticate with a relying party using their existing credentials. 15 | 16 | The `PublicKeyCredential` class is now designed for flexible use, allowing users to specify their desired authentication and attestation configurations directly. 17 | 18 | To use `PublicKeyCredential`, you need to provide the following parameters when initializing the class: 19 | 20 | - **authenticationMethod**: Define the method of authentication to use specific authenticator, such as biometric or device credential authenticator. 21 | - **attestationStatement**: Specify the format for the attestation statement. 22 | This setup allows you to customize the credential management process according to your specific security requirements. 23 | 24 | 25 | ### RelyingParty 26 | 27 | The `RelyingParty` establishes communication with your server to manage access to secure applications. In FIDO2, it generates and handles authentication requests, verifies responses from authenticators, and maintains user credentials, ensuring secure, password-less interactions between the client and server. 28 | Library users must implement the `RelyingParty` interface themselves. 29 | 30 | ### CredentialSourceStorage 31 | The `CredentialSourceStorage` is an interface that defines the behavior of a database for handling a public key credential source and its signature counter. 32 | 33 | ## Requirements 34 | - Android >= 9 (Pie) / API level >= 28 35 | 36 | 37 | ## Usage 38 | 39 | 40 | ### Step 1: Implement the `RelyingParty` Interface 41 | 42 | First, you need to create an implementation of the `RelyingParty` interface. This interface is crucial for handling communication with your server's FIDO2-compatible endpoints. 43 | 44 | To help you get started with your implementation, we recommend checking out a sample application available on GitHub: 45 | 46 | * [webauthndemo-kotlin/RelyingParty](https://github.com/line/webauthndemo-kotlin/blob/main/app/src/main/java/jp/co/lycorp/webauthn/sample/network/Fido2RelyingPartyImpl.kt) 47 | 48 | This sample provides a practical example of how to implement the `RelyingParty` interface in a real-world Android application. It will give you insights into integrating FIDO2 functionalities effectively with your server setup. 49 | 50 | ### Step 2: Implement the `CredentialSourceStorage` Interface 51 | 52 | Next, you need to create an implementation of the `CredentialSourceStorage ` interface to manage credential source and signature counter. 53 | 54 | To help you get started with your implementation, we recommend checking out a sample application available on GitHub: 55 | 56 | * [webauthndemo-kotlin/CredentialSourceStorage](https://github.com/line/webauthndemo-kotlin/blob/main/app/src/main/java/jp/co/lycorp/webauthn/sample/data/database/RoomCredentialSourceStorage.kt) 57 | 58 | ### Step 3: Initialize `PublicKeyCredential` 59 | Once you have your relying party and credential storage implementation ready, you can initialize the public key credential. 60 | 61 | 62 | ```kotlin 63 | val rp = YourRelyingParty() 64 | val db = YourCredentialSourceStorage() 65 | 66 | // You can use a biometric authenticator. 67 | val publicKeyCredential = PublicKeyCredential( 68 | rpClient = rp, 69 | db = db, 70 | authenticationMethod = AuthenticationMethod.Biometric, 71 | attestationStatement = AttestationStatementFormat.NONE, 72 | ) 73 | 74 | // ,or you can use a device credential. 75 | val publicKeyCredential = DeviceCredential( 76 | rpClient = rp, 77 | db = db, 78 | authenticationMethod = AuthenticationMethod.DeviceCredential, 79 | attestationStatement = AttestationStatementFormat.NONE, 80 | ) 81 | 82 | // You can use attestation using AttestationStatementFormat.ANDROID_KEY. 83 | val publicKeyCredential = DeviceCredential( 84 | rpClient = rp, 85 | db = db, 86 | authenticationMethod = AuthenticationMethod.Biometric, 87 | attestationStatement = AttestationStatementFormat.ANDROID_KEY, 88 | ) 89 | ``` 90 | 91 | Here, activity refers to the instance of your current Activity from which you are initiating the authentication process. This allows the `PublicKeyCredential` to interact with the user interface for authentication. 92 | 93 | ### Step 4: Register and Authenticate Credentials 94 | Before using the `create` and `get` methods of `publicKeyCredential`, configure `options` and `fido2PromptInfo` according to your needs. These configurations will be used for both registration and authentication processes. 95 | 96 | When you call the `create` method to register a new credential, or the `get` method to authenticate using an existing credential, the methods will return a `Result` type: 97 | 98 | 99 | #### Registering a Credential 100 | Register a new credential using the `create` method: 101 | 102 | ```kotlin 103 | val result: Result = publicKeyCredential.create( 104 | activity = activity, 105 | options = registrationOptions, 106 | fido2PromptInfo = fido2PromptInfo, 107 | ) 108 | ``` 109 | 110 | #### Authenticating with a Credential 111 | Authenticate using an existing credential with the `get` method: 112 | 113 | ```kotlin 114 | val result: Result = publicKeyCredential.get( 115 | activity = activity, 116 | options = authenticationOptions, 117 | fido2PromptInfo = fido2PromptInfo, 118 | ) 119 | ``` 120 | 121 | ## License 122 | Apache License 2.0. See [`LICENSE`](./LICENSE). 123 | 124 | 125 | ## Contact Information 126 | 127 | We are dedicated to making our work open-source to assist with your specific needs. We are eager to learn how this library is being utilized and the issues it resolves for you. To communicate, we recommend the following approach: 128 | 129 | * For reporting bugs, proposing improvements, or asking questions about the library, please utilize the [**Issues**](https://github.com/line/webauthn-kotlin/issues) section of our GitHub repository. Your feedback is invaluable in helping us address your concerns more effectively and enhances the community's experience. 130 | 131 | Please avoid sharing any sensitive or confidential information in the issues. If there is a need to discuss sensitive matters, please indicate so in your issue, and we will arrange a more secure communication method. 132 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | buildscript { 18 | ext.kotlin_version = "$project.kotlinVersion" 19 | repositories { 20 | google() 21 | mavenCentral() 22 | } 23 | dependencies { 24 | classpath 'com.android.tools.build:gradle:7.4.2' 25 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21" 26 | classpath "de.mannodermaus.gradle.plugins:android-junit5:1.9.3.0" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true 24 | android.defaults.buildfeatures.buildconfig=true 25 | android.nonFinalResIds=false 26 | versionMajor=1 27 | versionMinor=1 28 | versionPatch=0 29 | snapshotBuild=false 30 | 31 | kotlinVersion=2.0.21 32 | coreVersion=1.10.0 33 | appcompatVersion=1.6.1 34 | kotlinxCoroutinesVersion=1.7.0 35 | mockkVersion=1.13.8 36 | kotestVersion=5.8.0 37 | roomVersion=2.5.2 38 | espressoVersion=3.5.1 39 | kotlinTestJunitVersion=1.7.20 40 | assertJVersion=3.22.0 41 | biometricVersion=1.1.0 42 | kotlinxSerializationVersion=1.4.1 43 | gsonVersion=2.10.1 44 | junit5Version=5.9.3 45 | fragmentTestingVersion=1.6.0 46 | truthVersion=1.4.4 47 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/line/webauthn-kotlin/979efbca1e5428c34f53b995c660941388152a41/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Jan 23 19:28:06 KST 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.4-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | gradlePluginPortal() 6 | } 7 | } 8 | dependencyResolutionManagement { 9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 10 | repositories { 11 | google() 12 | mavenCentral() 13 | } 14 | } 15 | rootProject.name = "webauthn-kotlin" 16 | include ':webauthn' 17 | -------------------------------------------------------------------------------- /webauthn/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /webauthn/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | import org.codehaus.groovy.runtime.GStringImpl 18 | import org.jetbrains.kotlin.gradle.tasks.KaptGenerateStubs 19 | 20 | buildscript { 21 | project.ext.isSnapshot = project.snapshotBuild.toBoolean() 22 | 23 | def commitId = "git rev-parse --short HEAD".execute().text.trim() 24 | 25 | if (project.ext.isSnapshot) { 26 | project.ext.versionName = "${project.versionMajor}.${project.versionMinor}.${project.versionPatch}-${commitId}-SNAPSHOT" as GStringImpl 27 | } else { 28 | project.ext.versionName = "${project.versionMajor}.${project.versionMinor}.${project.versionPatch}" as GStringImpl 29 | } 30 | } 31 | 32 | 33 | plugins { 34 | id "maven-publish" 35 | id "com.android.library" 36 | id "kotlin-android" 37 | id "com.google.devtools.ksp" version "2.0.21-1.0.28" 38 | id "org.jetbrains.kotlin.android" 39 | id "de.mannodermaus.android-junit5" 40 | id "org.jlleitschuh.gradle.ktlint" version "12.0.3" 41 | } 42 | 43 | android { 44 | namespace "jp.co.lycorp.webauthn" 45 | compileSdk 34 46 | 47 | defaultConfig { 48 | minSdkVersion 28 49 | targetSdk 33 50 | versionCode 1 51 | versionName "1.0" 52 | 53 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 54 | testInstrumentationRunnerArgument("runnerBuilder", "de.mannodermaus.junit5.AndroidJUnit5Builder") 55 | } 56 | buildTypes { 57 | release { 58 | minifyEnabled false 59 | proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" 60 | } 61 | } 62 | compileOptions { 63 | sourceCompatibility = JavaVersion.VERSION_11 64 | targetCompatibility = JavaVersion.VERSION_11 65 | } 66 | kotlinOptions { 67 | jvmTarget = "11" 68 | } 69 | testOptions { 70 | unitTests.all { 71 | it.useJUnitPlatform() 72 | } 73 | unitTests { 74 | includeAndroidResources = true 75 | } 76 | } 77 | packagingOptions { 78 | resources { 79 | excludes += "/META-INF/{AL2.0,LGPL2.1,LICENSE.md,LICENSE-notice.md,NOTICE.md}" 80 | } 81 | } 82 | } 83 | 84 | tasks.withType(KaptGenerateStubs).configureEach{kotlinOptions{jvmTarget = "11"}} 85 | 86 | kotlin { 87 | jvmToolchain(11) 88 | } 89 | 90 | dependencies { 91 | implementation "androidx.core:core-ktx:$project.coreVersion" 92 | implementation "androidx.appcompat:appcompat:$project.appcompatVersion" 93 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$project.kotlinxCoroutinesVersion" 94 | 95 | // library for test 96 | androidTestImplementation "org.jetbrains.kotlin:kotlin-test-junit:$project.kotlinTestJunitVersion" 97 | androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$project.kotlinxCoroutinesVersion" 98 | androidTestImplementation "androidx.test.espresso:espresso-core:$project.espressoVersion" 99 | androidTestImplementation "io.mockk:mockk-android:$project.mockkVersion" 100 | androidTestImplementation "androidx.fragment:fragment-testing:$project.fragmentTestingVersion" 101 | testImplementation "io.mockk:mockk-android:$project.mockkVersion" 102 | testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$project.kotlinTestJunitVersion" 103 | testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$project.kotlinxCoroutinesVersion" 104 | 105 | // junit5 106 | testImplementation platform("org.junit:junit-bom:$project.junit5Version") 107 | testImplementation "org.junit.jupiter:junit-jupiter-api" 108 | testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine" 109 | testImplementation "org.junit.jupiter:junit-jupiter-params:$project.junit5Version" 110 | 111 | androidTestImplementation platform("org.junit:junit-bom:$project.junit5Version") 112 | androidTestImplementation "org.junit.jupiter:junit-jupiter-api" 113 | androidTestRuntimeOnly "org.junit.jupiter:junit-jupiter-engine" 114 | androidTestImplementation "org.junit.jupiter:junit-jupiter-params:$project.junit5Version" 115 | 116 | // truth 117 | androidTestImplementation("com.google.truth:truth:$project.truthVersion") 118 | testImplementation("com.google.truth:truth:$project.truthVersion") 119 | 120 | // cbor 121 | implementation group: "co.nstant.in", name: "cbor", version: "0.9" 122 | 123 | // coroutine 124 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$project.kotlinxCoroutinesVersion" 125 | 126 | // androidx biometric 127 | implementation "androidx.biometric:biometric:$project.biometricVersion" 128 | 129 | // Room 130 | implementation "androidx.room:room-runtime:$project.roomVersion" 131 | ksp "androidx.room:room-compiler:$project.roomVersion" 132 | implementation "androidx.room:room-ktx:$project.roomVersion" 133 | androidTestImplementation "androidx.room:room-testing:$project.roomVersion" 134 | 135 | // serialization 136 | implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:$project.kotlinxSerializationVersion" 137 | 138 | // Gson 139 | implementation "com.google.code.gson:gson:$project.gsonVersion" 140 | 141 | implementation "org.jetbrains.kotlin:kotlin-reflect:$project.kotlinVersion" 142 | } 143 | 144 | android.libraryVariants.configureEach { variant -> 145 | variant.outputs.all { 146 | outputFileName = "webauthn-kotlin-release.aar" 147 | } 148 | } 149 | 150 | publishing { 151 | publications { 152 | webauthnKotlinAar(MavenPublication) { 153 | groupId = "jp.co.lycorp.webauthn" 154 | artifactId = "webauthn-kotlin" 155 | version = project.ext.versionName 156 | pom { 157 | name = "webauthn-kotlin" 158 | description = "A Kotlin library for implementing WebAuthn authentication in Android applications." 159 | url = "https://github.com/line/webauthn-kotlin" 160 | } 161 | artifact("$buildDir/outputs/aar/webauthn-kotlin-release.aar") 162 | pom.withXml { 163 | final dependenciesNode = asNode().appendNode('dependencies') 164 | 165 | configurations.implementation.allDependencies.each { 166 | final dependencyNode = dependenciesNode.appendNode('dependency') 167 | dependencyNode.appendNode('groupId', it.group) 168 | dependencyNode.appendNode('artifactId', it.name) 169 | dependencyNode.appendNode('version', it.version) 170 | } 171 | 172 | configurations.api.allDependencies.each { 173 | final dependencyNode = dependenciesNode.appendNode('dependency') 174 | dependencyNode.appendNode('groupId', it.group) 175 | dependencyNode.appendNode('artifactId', it.name) 176 | dependencyNode.appendNode('version', it.version) 177 | } 178 | } 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /webauthn/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | 23 | -keep class jp.co.lycorp.webauthn.** { *; } 24 | -dontwarn java.lang.invoke.StringConcatFactory 25 | -------------------------------------------------------------------------------- /webauthn/src/androidTest/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /webauthn/src/androidTest/java/jp/co/lycorp/webauthn/AuthenticatorTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn 18 | 19 | import androidx.fragment.app.FragmentActivity 20 | import androidx.test.core.app.ActivityScenario 21 | import com.google.common.truth.Truth.assertThat 22 | import com.google.common.truth.Truth.assertWithMessage 23 | import io.mockk.coEvery 24 | import io.mockk.every 25 | import io.mockk.mockk 26 | import io.mockk.slot 27 | import java.security.KeyStore 28 | import java.security.Signature 29 | import jp.co.lycorp.webauthn.authenticator.Authenticator 30 | import jp.co.lycorp.webauthn.authenticator.keygenerator.BiometricKeyGenerator 31 | import jp.co.lycorp.webauthn.authenticator.keygenerator.DeviceCredentialKeyGenerator 32 | import jp.co.lycorp.webauthn.authenticator.keygenerator.Fido2KeyGenerator 33 | import jp.co.lycorp.webauthn.authenticator.objectgenerator.AndroidKeyObjectGenerator 34 | import jp.co.lycorp.webauthn.authenticator.objectgenerator.NoneObjectGenerator 35 | import jp.co.lycorp.webauthn.handler.BiometricAuthenticationHandler 36 | import jp.co.lycorp.webauthn.model.AuthenticatorType 37 | import jp.co.lycorp.webauthn.model.COSEAlgorithmIdentifier 38 | import jp.co.lycorp.webauthn.model.Fido2UserAuthResult 39 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialParams 40 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialRpEntity 41 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialType 42 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialUserEntity 43 | import jp.co.lycorp.webauthn.util.MockCredentialSourceStorage 44 | import jp.co.lycorp.webauthn.util.TestFragmentActivity 45 | import kotlinx.coroutines.runBlocking 46 | import org.junit.jupiter.api.BeforeEach 47 | import org.junit.jupiter.api.DisplayName 48 | import org.junit.jupiter.params.ParameterizedTest 49 | import org.junit.jupiter.params.provider.MethodSource 50 | 51 | class AuthenticatorTest { 52 | private lateinit var authenticator: Authenticator 53 | private var mockCredentialSourceStorage = MockCredentialSourceStorage() 54 | private val mockAuthenticationHandler: BiometricAuthenticationHandler = mockk() 55 | private val keyStore: KeyStore = KeyStore.getInstance("AndroidKeyStore").also { 56 | it.load(null) 57 | } 58 | 59 | private lateinit var dummyHash: ByteArray 60 | private lateinit var dummyRpEntity: PublicKeyCredentialRpEntity 61 | private lateinit var dummyUserEntity: PublicKeyCredentialUserEntity 62 | private lateinit var dummyCredParams: List 63 | private lateinit var dummyRpId: String 64 | private lateinit var dummyByteArray: ByteArray 65 | 66 | companion object { 67 | @JvmStatic 68 | fun authenticatorTypes() = listOf( 69 | AuthenticatorType.BiometricNone, 70 | AuthenticatorType.BiometricAndroidKey, 71 | AuthenticatorType.DeviceCredentialNone, 72 | AuthenticatorType.DeviceCredentialAndroidKey 73 | ) 74 | } 75 | 76 | @BeforeEach 77 | fun setUp() { 78 | dummyHash = ByteArray(32) { 0 } 79 | dummyRpEntity = PublicKeyCredentialRpEntity("example.com", "Example Relying Party") 80 | dummyUserEntity = PublicKeyCredentialUserEntity("user123", "User Name", "Display Name") 81 | dummyCredParams = listOf( 82 | PublicKeyCredentialParams(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256) 83 | ) 84 | dummyRpId = "example.com" 85 | dummyByteArray = ByteArray(32) { 2 } 86 | 87 | coEvery { mockAuthenticationHandler.isSupported(any()) } returns true 88 | val signatureSlot = slot<(() -> Signature)?>() 89 | coEvery { 90 | mockAuthenticationHandler.authenticate( 91 | any(), 92 | any(), 93 | captureNullable(signatureSlot), 94 | ) 95 | } coAnswers { 96 | val capturedSignature = signatureSlot.captured 97 | if (capturedSignature == null) { 98 | Fido2UserAuthResult(signature = null) 99 | } else { 100 | Fido2UserAuthResult(signature = capturedSignature()) 101 | } 102 | } 103 | } 104 | 105 | private fun assignAuthenticator(authType: AuthenticatorType) { 106 | val mockKeyGenerator = mockk() 107 | 108 | val keyAliasSlot = slot() 109 | val challengeSlot = slot() 110 | val publicKeyAlgorithmSlot = slot() 111 | val isStrongBoxBackedSlot = slot() 112 | 113 | val realKeyGenerator = when (authType) { 114 | AuthenticatorType.BiometricNone -> BiometricKeyGenerator() 115 | AuthenticatorType.BiometricAndroidKey -> BiometricKeyGenerator() 116 | AuthenticatorType.DeviceCredentialNone -> DeviceCredentialKeyGenerator() 117 | AuthenticatorType.DeviceCredentialAndroidKey -> DeviceCredentialKeyGenerator() 118 | } 119 | 120 | every { 121 | mockKeyGenerator.generateFido2Key( 122 | keyAlias = capture(keyAliasSlot), 123 | challenge = captureNullable(challengeSlot), 124 | publicKeyAlgorithm = capture(publicKeyAlgorithmSlot), 125 | isStrongBoxBacked = capture(isStrongBoxBackedSlot), 126 | userAuthenticationRequired = any() 127 | ) 128 | } answers { 129 | realKeyGenerator.generateFido2Key( 130 | keyAlias = keyAliasSlot.captured, 131 | challenge = challengeSlot.captured, 132 | publicKeyAlgorithm = publicKeyAlgorithmSlot.captured, 133 | isStrongBoxBacked = isStrongBoxBackedSlot.captured, 134 | userAuthenticationRequired = false // Override the value to false 135 | ) 136 | } 137 | 138 | authenticator = when (authType) { 139 | AuthenticatorType.BiometricNone -> Authenticator( 140 | db = mockCredentialSourceStorage, 141 | authenticationHandler = mockAuthenticationHandler, 142 | fido2KeyGenerator = mockKeyGenerator, 143 | fido2ObjectGenerator = NoneObjectGenerator(), 144 | authType = authType, 145 | ) 146 | 147 | AuthenticatorType.BiometricAndroidKey -> Authenticator( 148 | db = mockCredentialSourceStorage, 149 | authenticationHandler = mockAuthenticationHandler, 150 | fido2KeyGenerator = mockKeyGenerator, 151 | fido2ObjectGenerator = AndroidKeyObjectGenerator(), 152 | authType = authType, 153 | ) 154 | 155 | AuthenticatorType.DeviceCredentialNone -> Authenticator( 156 | db = mockCredentialSourceStorage, 157 | authenticationHandler = mockAuthenticationHandler, 158 | fido2KeyGenerator = mockKeyGenerator, 159 | fido2ObjectGenerator = NoneObjectGenerator(), 160 | authType = authType, 161 | ) 162 | 163 | AuthenticatorType.DeviceCredentialAndroidKey -> Authenticator( 164 | db = mockCredentialSourceStorage, 165 | authenticationHandler = mockAuthenticationHandler, 166 | fido2KeyGenerator = mockKeyGenerator, 167 | fido2ObjectGenerator = AndroidKeyObjectGenerator(), 168 | authType = authType, 169 | ) 170 | } 171 | } 172 | 173 | private fun checkMakeCredentialAndGetAssertion(activity: FragmentActivity, authenticator: Authenticator) { 174 | runBlocking { 175 | val aliasListBefore = keyStore.aliases().toList() 176 | authenticator.makeCredential( 177 | activity = activity, 178 | hash = dummyHash, 179 | rpEntity = dummyRpEntity, 180 | userEntity = dummyUserEntity, 181 | credTypesAndPubKeyAlgs = dummyCredParams, 182 | excludeCredDescriptorList = null, 183 | extensions = null, 184 | ) 185 | val aliasListAfter = keyStore.aliases().toList() 186 | 187 | assertThat(aliasListAfter.size).isEqualTo(aliasListBefore.size + 1) 188 | 189 | val newAlias = aliasListAfter.minus(aliasListBefore.toSet()).first() 190 | val newCredId = newAlias 191 | 192 | assertThat(mockCredentialSourceStorage.load(newCredId)).isNotNull() 193 | 194 | authenticator.getAssertion( 195 | activity = activity, 196 | rpId = dummyRpId, 197 | hash = dummyByteArray, 198 | allowCredDescriptorList = null, 199 | extensions = null 200 | ) 201 | 202 | // Erase a key and a credential for next tests 203 | keyStore.deleteEntry(newAlias) 204 | mockCredentialSourceStorage.delete(newAlias) 205 | } 206 | } 207 | 208 | @ParameterizedTest(name = "{0}") 209 | @MethodSource("authenticatorTypes") 210 | @DisplayName("Authenticators are functioning properly.") 211 | fun testAuthenticator(authType: AuthenticatorType) { 212 | ActivityScenario.launch(TestFragmentActivity::class.java).use { scenario -> 213 | scenario.onActivity { activity: TestFragmentActivity -> 214 | assignAuthenticator(authType) 215 | try { 216 | checkMakeCredentialAndGetAssertion(activity, authenticator) 217 | } catch (e: Exception) { 218 | assertWithMessage("Expected no exception, but got: ${e.message}") 219 | .fail() 220 | } 221 | } 222 | } 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /webauthn/src/androidTest/java/jp/co/lycorp/webauthn/authenticator/keygenerator/Fido2KeyGeneratorTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator.keygenerator 18 | 19 | import com.google.common.truth.Truth.assertThat 20 | import java.security.KeyStore 21 | import jp.co.lycorp.webauthn.model.COSEAlgorithmIdentifier 22 | import jp.co.lycorp.webauthn.util.Fido2Util 23 | import jp.co.lycorp.webauthn.util.toBase64url 24 | import org.junit.jupiter.api.AfterEach 25 | import org.junit.jupiter.api.Test 26 | 27 | class Fido2KeyGeneratorTest { 28 | 29 | private val generatedAliases = mutableListOf() 30 | 31 | private fun generateRandomAlias(): String { 32 | return Fido2Util.generateRandomByteArray(32).toBase64url() 33 | } 34 | 35 | private fun testKeyGenerator(keyGenerator: jp.co.lycorp.webauthn.authenticator.keygenerator.Fido2KeyGenerator) { 36 | val challenges = arrayOf(null, ByteArray(32) { it.toByte() }) 37 | val strongBoxOptions = arrayOf(true, false) 38 | 39 | for (challenge in challenges) { 40 | for (isStrongBoxBacked in strongBoxOptions) { 41 | val keyAlias = generateRandomAlias() 42 | generatedAliases.add(keyAlias) 43 | 44 | try { 45 | keyGenerator.generateFido2Key( 46 | keyAlias = keyAlias, 47 | challenge = challenge, 48 | publicKeyAlgorithm = COSEAlgorithmIdentifier.ES256, 49 | isStrongBoxBacked = isStrongBoxBacked 50 | ) 51 | } catch (e: Exception) { 52 | assertThat(e).isNull() 53 | } 54 | 55 | val keyStore = KeyStore.getInstance("AndroidKeyStore").also { 56 | it.load(null) 57 | } 58 | assertThat(keyStore.containsAlias(keyAlias)).isTrue() 59 | } 60 | } 61 | } 62 | 63 | @Test 64 | fun testBiometricKeyGeneratorGenerateFido2Key() { 65 | val keyGenerator = jp.co.lycorp.webauthn.authenticator.keygenerator.BiometricKeyGenerator() 66 | testKeyGenerator(keyGenerator) 67 | } 68 | 69 | @Test 70 | fun testDeviceCredentialKeyGeneratorGenerateFido2Key() { 71 | val keyGenerator = 72 | jp.co.lycorp.webauthn.authenticator.keygenerator.DeviceCredentialKeyGenerator() 73 | testKeyGenerator(keyGenerator) 74 | } 75 | 76 | @AfterEach 77 | fun tearDown() { 78 | val keyStore = KeyStore.getInstance("AndroidKeyStore").also { 79 | it.load(null) 80 | } 81 | for (alias in generatedAliases) { 82 | if (keyStore.containsAlias(alias)) { 83 | keyStore.deleteEntry(alias) 84 | } 85 | } 86 | generatedAliases.clear() 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /webauthn/src/androidTest/java/jp/co/lycorp/webauthn/authenticator/objectgenerator/Fido2ObjectGeneratorTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator.objectgenerator 18 | 19 | import android.security.keystore.KeyGenParameterSpec 20 | import android.security.keystore.KeyProperties 21 | import com.google.common.truth.Truth.assertThat 22 | import java.security.KeyPair 23 | import java.security.KeyPairGenerator 24 | import java.security.Signature 25 | import jp.co.lycorp.webauthn.model.AndroidKeyAttestationStatement 26 | import jp.co.lycorp.webauthn.model.AttestationObject 27 | import jp.co.lycorp.webauthn.model.AuthenticatorExtensionsOutput 28 | import jp.co.lycorp.webauthn.model.COSEAlgorithmIdentifier 29 | import jp.co.lycorp.webauthn.model.NoneAttestationStatement 30 | import jp.co.lycorp.webauthn.model.getSignatureAlgorithmName 31 | import jp.co.lycorp.webauthn.util.Fido2Util 32 | import jp.co.lycorp.webauthn.util.SecureExecutionHelper 33 | import jp.co.lycorp.webauthn.util.toBase64url 34 | import org.junit.jupiter.api.AfterEach 35 | import org.junit.jupiter.api.BeforeEach 36 | import org.junit.jupiter.api.Test 37 | 38 | class Fido2ObjectGeneratorTest { 39 | 40 | private lateinit var hash: ByteArray 41 | private lateinit var rpId: String 42 | private lateinit var aaguid: ByteArray 43 | private lateinit var credId: String 44 | private lateinit var keyAlias: String 45 | private var signCount: UInt = 0u 46 | private var extensions: AuthenticatorExtensionsOutput? = null 47 | private var signature: Signature? = null 48 | 49 | @BeforeEach 50 | fun setUp() { 51 | hash = ByteArray(32) 52 | rpId = "example.com" 53 | aaguid = ByteArray(16) 54 | credId = Fido2Util.generateRandomByteArray(32).toBase64url() 55 | signCount = 1u 56 | extensions = null 57 | keyAlias = credId 58 | } 59 | 60 | private fun createAttestationObject(generator: Fido2ObjectGenerator): AttestationObject { 61 | val attestationObject: AttestationObject = generator.createAttestationObject( 62 | hash, 63 | rpId, 64 | aaguid, 65 | credId, 66 | signCount, 67 | extensions, 68 | signature 69 | ) 70 | 71 | assertThat(attestationObject).isNotNull() 72 | assertThat(attestationObject.fmt).isEqualTo(generator.fmt.value) 73 | return attestationObject 74 | } 75 | 76 | @Test 77 | fun testNoneObjectGeneratorCreateAttestationObject() { 78 | generateKey(keyAlias) 79 | signature = null 80 | val generator = NoneObjectGenerator() 81 | val attestationObject = createAttestationObject(generator) 82 | assertThat(attestationObject.attStmt).isInstanceOf(NoneAttestationStatement::class.java) 83 | } 84 | 85 | @Test 86 | fun testAndroidKeyObjectGeneratorCreateAttestationObject() { 87 | val keyPair = generateKey(keyAlias) 88 | signature = Signature.getInstance( 89 | COSEAlgorithmIdentifier.ES256.getSignatureAlgorithmName() 90 | ).apply { initSign(keyPair.private) } 91 | val generator = AndroidKeyObjectGenerator() 92 | val attestationObject = createAttestationObject(generator) 93 | assertThat(attestationObject.attStmt).isInstanceOf(AndroidKeyAttestationStatement::class.java) 94 | 95 | val verificationSignature = Signature.getInstance("SHA256withECDSA") 96 | verificationSignature.initVerify(keyPair.public) 97 | verificationSignature.update(attestationObject.authData + hash) 98 | val androidKeyAttestationStatement = attestationObject.attStmt as? AndroidKeyAttestationStatement 99 | val isVerified = verificationSignature.verify(androidKeyAttestationStatement!!.sig) 100 | assertThat(isVerified).isTrue() 101 | } 102 | 103 | @AfterEach 104 | fun tearDown() { 105 | SecureExecutionHelper.deleteKey(keyAlias) 106 | } 107 | 108 | private fun generateKey(alias: String): KeyPair { 109 | val keyPairGenerator = KeyPairGenerator.getInstance( 110 | KeyProperties.KEY_ALGORITHM_EC, 111 | "AndroidKeyStore" 112 | ) 113 | 114 | val keyGenParameterSpec = KeyGenParameterSpec.Builder( 115 | alias, 116 | KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY 117 | ).run { 118 | setDigests(KeyProperties.DIGEST_SHA256) 119 | setUserAuthenticationRequired(false) 120 | build() 121 | } 122 | 123 | keyPairGenerator.initialize(keyGenParameterSpec) 124 | return keyPairGenerator.generateKeyPair() 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /webauthn/src/androidTest/java/jp/co/lycorp/webauthn/util/MockCredentialSourceStorage.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.util 18 | 19 | import java.util.UUID 20 | import jp.co.lycorp.webauthn.db.CredentialSourceStorage 21 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialSource 22 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialType 23 | 24 | class MockCredentialSourceStorage : CredentialSourceStorage { 25 | private var credSourceTable: MutableList = mutableListOf() 26 | 27 | override fun store(credSource: PublicKeyCredentialSource) { 28 | val credSourceEntity = TestPubKeyCredSourceEntity( 29 | credType = PublicKeyCredentialType.PUBLIC_KEY.value, 30 | aaguid = credSource.aaguid, 31 | credId = credSource.id, 32 | rpId = credSource.rpId, 33 | userHandle = credSource.userHandle, 34 | signatureCounter = 0L, 35 | ) 36 | credSourceTable.add(credSourceEntity) 37 | } 38 | override fun load(credId: String): PublicKeyCredentialSource? { 39 | val credSourceEntity = credSourceTable.firstOrNull { it.credId.contentEquals(credId) } 40 | return credSourceEntity?.let { 41 | PublicKeyCredentialSource( 42 | type = it.credType, 43 | id = it.credId, 44 | rpId = it.rpId, 45 | userHandle = it.userHandle, 46 | aaguid = it.aaguid, 47 | ) 48 | } 49 | } 50 | 51 | override fun loadAll(aaguid: UUID?): List { 52 | return credSourceTable 53 | .filter { entity -> 54 | aaguid == null || entity.aaguid == aaguid 55 | } 56 | .map { entity -> 57 | PublicKeyCredentialSource( 58 | type = entity.credType, 59 | id = entity.credId, 60 | rpId = entity.rpId, 61 | userHandle = entity.userHandle, 62 | aaguid = entity.aaguid, 63 | ) 64 | } 65 | } 66 | 67 | override fun delete(credId: String) { 68 | credSourceTable = credSourceTable.filter { it.credId != credId }.toMutableList() 69 | } 70 | 71 | override fun increaseSignatureCounter(credId: String) { 72 | val credSourceEntity = credSourceTable.firstOrNull { it.credId.contentEquals(credId) } 73 | credSourceEntity?.let { 74 | it.signatureCounter += 1 75 | } 76 | } 77 | override fun getSignatureCounter(credId: String): UInt = 0u 78 | 79 | fun removeAllData() { 80 | credSourceTable = mutableListOf() 81 | } 82 | } 83 | 84 | data class TestPubKeyCredSourceEntity( 85 | val credType: String, 86 | var credId: String, 87 | val rpId: String, 88 | val userHandle: String?, 89 | val aaguid: UUID, 90 | var signatureCounter: Long, 91 | ) 92 | -------------------------------------------------------------------------------- /webauthn/src/androidTest/java/jp/co/lycorp/webauthn/util/TestFragmentActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.util 18 | 19 | import androidx.fragment.app.FragmentActivity 20 | 21 | class TestFragmentActivity : FragmentActivity() 22 | -------------------------------------------------------------------------------- /webauthn/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/authenticator/AuthenticatorProvider.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator 18 | 19 | import jp.co.lycorp.webauthn.authenticator.keygenerator.BiometricKeyGenerator 20 | import jp.co.lycorp.webauthn.authenticator.keygenerator.DeviceCredentialKeyGenerator 21 | import jp.co.lycorp.webauthn.authenticator.objectgenerator.AndroidKeyObjectGenerator 22 | import jp.co.lycorp.webauthn.authenticator.objectgenerator.NoneObjectGenerator 23 | import jp.co.lycorp.webauthn.db.CredentialSourceStorage 24 | import jp.co.lycorp.webauthn.handler.BiometricAuthenticationHandler 25 | import jp.co.lycorp.webauthn.handler.DeviceCredentialAuthenticationHandler 26 | import jp.co.lycorp.webauthn.model.AttestationStatementFormat 27 | import jp.co.lycorp.webauthn.model.AuthenticationMethod 28 | import jp.co.lycorp.webauthn.model.AuthenticatorType 29 | import jp.co.lycorp.webauthn.model.Fido2PromptInfo 30 | import kotlinx.coroutines.CoroutineDispatcher 31 | import kotlinx.coroutines.Dispatchers 32 | 33 | class AuthenticatorProvider( 34 | private val db: CredentialSourceStorage, 35 | private val databaseDispatcher: CoroutineDispatcher = Dispatchers.IO, 36 | private val authenticationDispatcher: CoroutineDispatcher = Dispatchers.Main, 37 | ) { 38 | internal fun getAuthenticator( 39 | authenticationMethod: AuthenticationMethod, 40 | attestationStatement: AttestationStatementFormat, 41 | fido2PromptInfo: Fido2PromptInfo? = null, 42 | ): Authenticator { 43 | val authenticationHandler = when (authenticationMethod) { 44 | AuthenticationMethod.Biometric -> BiometricAuthenticationHandler( 45 | authenticationDispatcher 46 | ) 47 | AuthenticationMethod.DeviceCredential -> DeviceCredentialAuthenticationHandler( 48 | authenticationDispatcher 49 | ) 50 | } 51 | val fido2KeyGenerator = when (authenticationMethod) { 52 | AuthenticationMethod.Biometric -> BiometricKeyGenerator() 53 | AuthenticationMethod.DeviceCredential -> DeviceCredentialKeyGenerator() 54 | } 55 | val fido2ObjectGenerator = when (attestationStatement) { 56 | AttestationStatementFormat.NONE -> NoneObjectGenerator() 57 | AttestationStatementFormat.ANDROID_KEY -> AndroidKeyObjectGenerator() 58 | else -> AndroidKeyObjectGenerator() 59 | } 60 | val authType: AuthenticatorType = AuthenticatorType.getAuthenticatorType( 61 | authenticationMethod, 62 | attestationStatement 63 | ) 64 | 65 | return Authenticator( 66 | db = db, 67 | authenticationHandler = authenticationHandler, 68 | fido2KeyGenerator = fido2KeyGenerator, 69 | fido2ObjectGenerator = fido2ObjectGenerator, 70 | authType = authType, 71 | fido2PromptInfo = fido2PromptInfo, 72 | databaseDispatcher = databaseDispatcher, 73 | ) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/authenticator/keygenerator/BiometricKeyGenerator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator.keygenerator 18 | 19 | import android.security.keystore.KeyGenParameterSpec 20 | import android.security.keystore.KeyProperties 21 | import android.security.keystore.StrongBoxUnavailableException 22 | import java.security.KeyPair 23 | import java.security.KeyPairGenerator 24 | import jp.co.lycorp.webauthn.model.COSEAlgorithmIdentifier 25 | import jp.co.lycorp.webauthn.model.getAlgorithmParameterSpec 26 | import jp.co.lycorp.webauthn.model.getDigests 27 | import jp.co.lycorp.webauthn.model.getKeyProperties 28 | import jp.co.lycorp.webauthn.model.getSignaturePaddings 29 | 30 | class BiometricKeyGenerator : Fido2KeyGenerator() { 31 | 32 | override fun generateFido2Key( 33 | keyAlias: String, 34 | challenge: ByteArray?, 35 | publicKeyAlgorithm: COSEAlgorithmIdentifier, 36 | isStrongBoxBacked: Boolean, 37 | userAuthenticationRequired: Boolean 38 | ): KeyPair { 39 | return if (isStrongBoxBacked) { 40 | return try { 41 | generateBiometricFido2Key(keyAlias, challenge, publicKeyAlgorithm, true, userAuthenticationRequired) 42 | } catch (e: StrongBoxUnavailableException) { 43 | generateBiometricFido2Key(keyAlias, challenge, publicKeyAlgorithm, false, userAuthenticationRequired) 44 | } 45 | } else { 46 | generateBiometricFido2Key(keyAlias, challenge, publicKeyAlgorithm, false, userAuthenticationRequired) 47 | } 48 | } 49 | 50 | private fun generateBiometricFido2Key( 51 | keyAlias: String, 52 | challenge: ByteArray?, 53 | publicKeyAlgorithm: COSEAlgorithmIdentifier, 54 | isStrongBoxBacked: Boolean, 55 | userAuthenticationRequired: Boolean 56 | ): KeyPair { 57 | synchronized(lock) { 58 | val keyProperties = publicKeyAlgorithm.getKeyProperties() 59 | ?: throw IllegalArgumentException("Unsupported algorithm") 60 | val kpg: KeyPairGenerator = 61 | KeyPairGenerator.getInstance( 62 | keyProperties, 63 | "AndroidKeyStore", 64 | ) 65 | val parameterSpec: KeyGenParameterSpec = 66 | KeyGenParameterSpec.Builder( 67 | keyAlias, 68 | KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY, 69 | ).run { 70 | setIsStrongBoxBacked(isStrongBoxBacked) 71 | publicKeyAlgorithm.getSignaturePaddings()?.let { 72 | setSignaturePaddings(it) 73 | } 74 | publicKeyAlgorithm.getAlgorithmParameterSpec()?.let { 75 | setAlgorithmParameterSpec(it) 76 | } 77 | publicKeyAlgorithm.getDigests()?.let { 78 | setDigests(it) 79 | } 80 | setUserAuthenticationRequired(userAuthenticationRequired) 81 | setInvalidatedByBiometricEnrollment(true) 82 | if (challenge != null) { 83 | setAttestationChallenge(challenge) 84 | } 85 | build() 86 | } 87 | kpg.initialize(parameterSpec) 88 | return kpg.generateKeyPair() 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/authenticator/keygenerator/DeviceCredentialKeyGenerator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator.keygenerator 18 | 19 | import android.os.Build 20 | import android.security.keystore.KeyGenParameterSpec 21 | import android.security.keystore.KeyProperties 22 | import android.security.keystore.StrongBoxUnavailableException 23 | import java.security.KeyPair 24 | import java.security.KeyPairGenerator 25 | import jp.co.lycorp.webauthn.model.COSEAlgorithmIdentifier 26 | import jp.co.lycorp.webauthn.model.getAlgorithmParameterSpec 27 | import jp.co.lycorp.webauthn.model.getDigests 28 | import jp.co.lycorp.webauthn.model.getKeyProperties 29 | import jp.co.lycorp.webauthn.model.getSignaturePaddings 30 | 31 | class DeviceCredentialKeyGenerator : Fido2KeyGenerator() { 32 | 33 | override fun generateFido2Key( 34 | keyAlias: String, 35 | challenge: ByteArray?, 36 | publicKeyAlgorithm: COSEAlgorithmIdentifier, 37 | isStrongBoxBacked: Boolean, 38 | userAuthenticationRequired: Boolean 39 | ): KeyPair { 40 | return if (isStrongBoxBacked) { 41 | return try { 42 | generateDeviceCredentialFido2Key( 43 | keyAlias, 44 | challenge, 45 | publicKeyAlgorithm, 46 | true, 47 | userAuthenticationRequired 48 | ) 49 | } catch (e: StrongBoxUnavailableException) { 50 | generateDeviceCredentialFido2Key( 51 | keyAlias, 52 | challenge, 53 | publicKeyAlgorithm, 54 | false, 55 | userAuthenticationRequired 56 | ) 57 | } 58 | } else { 59 | generateDeviceCredentialFido2Key(keyAlias, challenge, publicKeyAlgorithm, false, userAuthenticationRequired) 60 | } 61 | } 62 | 63 | private fun generateDeviceCredentialFido2Key( 64 | keyAlias: String, 65 | challenge: ByteArray?, 66 | publicKeyAlgorithm: COSEAlgorithmIdentifier, 67 | isStrongBoxBacked: Boolean, 68 | userAuthenticationRequired: Boolean, 69 | userAuthenticationValidityDurationSeconds: Int = 5 70 | ): KeyPair { 71 | synchronized(lock) { 72 | val keyProperties = publicKeyAlgorithm.getKeyProperties() 73 | ?: throw IllegalArgumentException("Unsupported algorithm") 74 | val kpg: KeyPairGenerator = KeyPairGenerator.getInstance(keyProperties, "AndroidKeyStore") 75 | val parameterSpec: KeyGenParameterSpec = 76 | KeyGenParameterSpec.Builder( 77 | keyAlias, 78 | KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY, 79 | ).run { 80 | setIsStrongBoxBacked(isStrongBoxBacked) 81 | publicKeyAlgorithm.getSignaturePaddings()?.let { 82 | setSignaturePaddings(it) 83 | } 84 | publicKeyAlgorithm.getAlgorithmParameterSpec()?.let { 85 | setAlgorithmParameterSpec(it) 86 | } 87 | publicKeyAlgorithm.getDigests()?.let { 88 | setDigests(it) 89 | } 90 | setUserAuthenticationRequired(userAuthenticationRequired) 91 | setInvalidatedByBiometricEnrollment(true) 92 | if (challenge != null) { 93 | setAttestationChallenge(challenge) 94 | } 95 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 96 | setUserAuthenticationParameters( 97 | 0, 98 | KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL 99 | ) 100 | } else { 101 | setUserAuthenticationValidityDurationSeconds(userAuthenticationValidityDurationSeconds) 102 | } 103 | build() 104 | } 105 | kpg.initialize(parameterSpec) 106 | return kpg.generateKeyPair() 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/authenticator/keygenerator/Fido2KeyGenerator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator.keygenerator 18 | 19 | import java.security.KeyPair 20 | import jp.co.lycorp.webauthn.model.COSEAlgorithmIdentifier 21 | 22 | abstract class Fido2KeyGenerator { 23 | val lock = Any() 24 | 25 | abstract fun generateFido2Key( 26 | keyAlias: String, 27 | challenge: ByteArray?, 28 | publicKeyAlgorithm: COSEAlgorithmIdentifier, 29 | isStrongBoxBacked: Boolean, 30 | userAuthenticationRequired: Boolean = true 31 | ): KeyPair 32 | } 33 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/authenticator/objectgenerator/AndroidKeyObjectGenerator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator.objectgenerator 18 | 19 | import java.security.MessageDigest 20 | import java.security.Signature 21 | import java.security.interfaces.ECPublicKey 22 | import jp.co.lycorp.webauthn.model.AndroidKeyAttestationStatement 23 | import jp.co.lycorp.webauthn.model.AttestationObject 24 | import jp.co.lycorp.webauthn.model.AttestationStatement 25 | import jp.co.lycorp.webauthn.model.AttestationStatementFormat 26 | import jp.co.lycorp.webauthn.model.AttestedCredData 27 | import jp.co.lycorp.webauthn.model.AuthenticatorExtensionsOutput 28 | import jp.co.lycorp.webauthn.model.COSEAlgorithmIdentifier 29 | import jp.co.lycorp.webauthn.model.EC2COSEKey 30 | import jp.co.lycorp.webauthn.util.SecureExecutionHelper 31 | import jp.co.lycorp.webauthn.util.base64urlToByteArray 32 | 33 | internal class AndroidKeyObjectGenerator : Fido2ObjectGenerator() { 34 | override val fmt: AttestationStatementFormat = AttestationStatementFormat.ANDROID_KEY 35 | 36 | override fun createAttestationObject( 37 | hash: ByteArray, 38 | rpId: String, 39 | aaguid: ByteArray, 40 | credId: String, 41 | signCount: UInt, 42 | extensions: AuthenticatorExtensionsOutput?, 43 | signature: Signature? 44 | ): AttestationObject { 45 | val credIdBytes = credId.base64urlToByteArray() 46 | val keyAlias = credId 47 | val publicKey = SecureExecutionHelper.getPublicKey(keyAlias) 48 | val encodedCredPubKey = EC2COSEKey(publicKey as ECPublicKey) 49 | .toCBOR() 50 | val rpIdHash = MessageDigest.getInstance("SHA-256").digest(rpId.toByteArray()) 51 | val attestedCredData = AttestedCredData( 52 | aaguid, 53 | credIdBytes, 54 | encodedCredPubKey 55 | ) 56 | val authenticatorData = 57 | createAuthenticatorData( 58 | signCount = signCount, 59 | rpIdHash = rpIdHash, 60 | extensions = extensions?.toCBOR(), 61 | attestedCredData = attestedCredData, 62 | ) 63 | val authenticatorDataBytes = authenticatorData.toByteArray() 64 | signature!!.update(authenticatorDataBytes + hash) 65 | val sig = signature.sign() 66 | val certChain = SecureExecutionHelper.getX509Certificates(keyAlias) 67 | val x5c = certChain.map { it.encoded } 68 | val attStmt: AttestationStatement = AndroidKeyAttestationStatement( 69 | alg = COSEAlgorithmIdentifier.ES256.value, 70 | sig = sig, 71 | x5c = x5c, 72 | ) 73 | 74 | return AttestationObject(authenticatorDataBytes, fmt.value, attStmt) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/authenticator/objectgenerator/Fido2ObjectGenerator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator.objectgenerator 18 | 19 | import java.security.MessageDigest 20 | import java.security.Signature 21 | import jp.co.lycorp.webauthn.model.AssertionObject 22 | import jp.co.lycorp.webauthn.model.AttestationObject 23 | import jp.co.lycorp.webauthn.model.AttestationStatementFormat 24 | import jp.co.lycorp.webauthn.model.AttestedCredData 25 | import jp.co.lycorp.webauthn.model.AuthenticatorData 26 | import jp.co.lycorp.webauthn.model.AuthenticatorDataFlags 27 | import jp.co.lycorp.webauthn.model.AuthenticatorExtensionsOutput 28 | 29 | internal abstract class Fido2ObjectGenerator { 30 | 31 | abstract val fmt: AttestationStatementFormat 32 | 33 | abstract fun createAttestationObject( 34 | hash: ByteArray, 35 | rpId: String, 36 | aaguid: ByteArray, 37 | credId: String, 38 | signCount: UInt, 39 | extensions: AuthenticatorExtensionsOutput?, 40 | signature: Signature? = null 41 | ): AttestationObject 42 | 43 | fun createAssertionObject( 44 | hash: ByteArray, 45 | rpId: String, 46 | signCount: UInt, 47 | signature: Signature, 48 | extensions: AuthenticatorExtensionsOutput?, 49 | ): AssertionObject { 50 | val rpIdHash = MessageDigest.getInstance("SHA-256").digest(rpId.toByteArray()) 51 | 52 | val authenticatorData = 53 | createAuthenticatorData( 54 | signCount = signCount, 55 | rpIdHash = rpIdHash, 56 | extensions = extensions?.toCBOR(), 57 | attestedCredData = null 58 | ) 59 | val authenticatorDataBytes = authenticatorData.toByteArray() 60 | signature.update(authenticatorDataBytes + hash) 61 | val sig = signature.sign() 62 | 63 | return AssertionObject( 64 | authenticatorDataBytes, 65 | sig, 66 | ) 67 | } 68 | 69 | protected fun createAuthenticatorData( 70 | signCount: UInt, 71 | rpIdHash: ByteArray, 72 | userPresent: Boolean = true, 73 | userVerified: Boolean = true, 74 | extensions: ByteArray? = null, 75 | attestedCredData: AttestedCredData?, 76 | ): AuthenticatorData { 77 | val attestedCredDataBytes = attestedCredData?.toByteArray() 78 | val flags = 79 | createFlags( 80 | userPresent, 81 | userVerified, 82 | attestedCredData != null, 83 | extensions, 84 | ) 85 | return AuthenticatorData( 86 | rpIdHash, 87 | flags, 88 | signCount, 89 | attestedCredDataBytes, 90 | extensions 91 | ) 92 | } 93 | 94 | protected fun createFlags( 95 | userPresent: Boolean, 96 | userVerified: Boolean, 97 | attestedCredDataIncluded: Boolean, 98 | extensions: ByteArray?, 99 | ): UByte { 100 | val up = userPresent 101 | val uv = userVerified 102 | val at = attestedCredDataIncluded 103 | val ed = extensions != null 104 | return AuthenticatorDataFlags.makeFlags(up, uv, at, ed) 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/authenticator/objectgenerator/NoneObjectGenerator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.authenticator.objectgenerator 18 | 19 | import java.security.MessageDigest 20 | import java.security.Signature 21 | import java.security.interfaces.ECPublicKey 22 | import jp.co.lycorp.webauthn.model.AttestationObject 23 | import jp.co.lycorp.webauthn.model.AttestationStatementFormat 24 | import jp.co.lycorp.webauthn.model.AttestedCredData 25 | import jp.co.lycorp.webauthn.model.AuthenticatorExtensionsOutput 26 | import jp.co.lycorp.webauthn.model.EC2COSEKey 27 | import jp.co.lycorp.webauthn.model.NoneAttestationStatement 28 | import jp.co.lycorp.webauthn.util.SecureExecutionHelper 29 | import jp.co.lycorp.webauthn.util.base64urlToByteArray 30 | 31 | internal class NoneObjectGenerator : Fido2ObjectGenerator() { 32 | override val fmt: AttestationStatementFormat = AttestationStatementFormat.NONE 33 | 34 | override fun createAttestationObject( 35 | hash: ByteArray, 36 | rpId: String, 37 | aaguid: ByteArray, 38 | credId: String, 39 | signCount: UInt, 40 | extensions: AuthenticatorExtensionsOutput?, 41 | signature: Signature? 42 | ): AttestationObject { 43 | val credIdBytes = credId.base64urlToByteArray() 44 | val keyAlias = credId 45 | val publicKey = SecureExecutionHelper.getPublicKey(keyAlias) 46 | val encodedCredPubKey = EC2COSEKey(publicKey as ECPublicKey).toCBOR() 47 | val rpIdHash = MessageDigest.getInstance("SHA-256").digest(rpId.toByteArray()) 48 | val attestedCredData = AttestedCredData( 49 | aaguid, 50 | credIdBytes, 51 | encodedCredPubKey 52 | ) 53 | val authenticatorData = 54 | createAuthenticatorData( 55 | signCount = signCount, 56 | rpIdHash = rpIdHash, 57 | extensions = extensions?.toCBOR(), 58 | attestedCredData = attestedCredData, 59 | ) 60 | val authenticatorDataBytes = authenticatorData.toByteArray() 61 | 62 | return AttestationObject(authenticatorDataBytes, fmt.value, NoneAttestationStatement()) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/db/CredentialSourceStorage.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.db 18 | 19 | import java.util.UUID 20 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialSource 21 | 22 | /** 23 | * Interface for storing and managing credential sources. 24 | */ 25 | interface CredentialSourceStorage { 26 | /** 27 | * Stores the given credential source. 28 | * 29 | * @param credSource The credential source to store. 30 | */ 31 | fun store(credSource: jp.co.lycorp.webauthn.model.PublicKeyCredentialSource) 32 | 33 | /** 34 | * Loads the credential source corresponding to the given credential ID. 35 | * 36 | * @param credId The ID of the credential source to load. 37 | * @return The loaded credential source, or null if not found. 38 | */ 39 | fun load(credId: String): jp.co.lycorp.webauthn.model.PublicKeyCredentialSource? 40 | 41 | /** 42 | * Loads all stored credential sources, optionally filtered by an AAGUID. 43 | * 44 | * If the `aaguid` parameter is null, the method returns all stored credential sources. 45 | * If a specific `aaguid` is provided, only the credential sources with the matching AAGUID are returned. 46 | * 47 | * @param aaguid Optional parameter to filter credential sources by AAGUID. 48 | * If null, all credential sources are loaded. 49 | * @return A list of credential sources, filtered by the specified AAGUID if provided. 50 | */ 51 | fun loadAll(aaguid: UUID? = null): List 52 | 53 | /** 54 | * Deletes the credential source corresponding to the given credential ID. 55 | * 56 | * @param credId The ID of the credential source to delete. 57 | */ 58 | fun delete(credId: String) 59 | 60 | /** 61 | * Gets the signature counter for the given credential ID. 62 | * 63 | * @param credId The ID of the credential source whose signature counter is to be retrieved. 64 | * @return The current value of the signature counter. 65 | */ 66 | fun getSignatureCounter(credId: String): UInt 67 | 68 | /** 69 | * Increases the signature counter for the given credential ID. 70 | * 71 | * @param credId The ID of the credential source whose signature counter is to be increased. 72 | */ 73 | fun increaseSignatureCounter(credId: String) 74 | } 75 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/exceptions/WebAuthnException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.exceptions 18 | 19 | sealed class WebAuthnException( 20 | override val message: String?, 21 | override val cause: Throwable? = null 22 | ) : Exception(message, cause) { 23 | 24 | sealed class CoreException(message: String?, cause: Throwable? = null) : WebAuthnException(message, cause) { 25 | class ConstraintException( 26 | message: String? = "A mutation operation in a transaction failed because a constraint was not satisfied.", 27 | cause: Throwable? = null 28 | ) : CoreException(message, cause) 29 | class InvalidStateException( 30 | message: String? = "The object is in an invalid state.", 31 | cause: Throwable? = null 32 | ) : CoreException(message, cause) 33 | class NotAllowedException( 34 | message: String? = "The request is not allowed by the user agent or the platform in the current context, " + 35 | "possibly because the user denied permission.", 36 | cause: Throwable? = null 37 | ) : CoreException(message, cause) 38 | class NotSupportedException( 39 | message: String? = "The operation is not supported.", 40 | cause: Throwable? = null 41 | ) : CoreException(message, cause) 42 | class TypeException( 43 | message: String? = null, 44 | cause: Throwable? = null 45 | ) : CoreException(message, cause) 46 | } 47 | 48 | class CredSrcStorageException(message: String?, cause: Throwable? = null) : WebAuthnException(message, cause) 49 | class RpException(message: String? = null, cause: Throwable? = null) : WebAuthnException(message, cause) 50 | sealed class AuthenticationException( 51 | message: String? = null, 52 | cause: Throwable? = null 53 | ) : WebAuthnException(message, cause) { 54 | class KeyPermanentlyInvalidatedException( 55 | message: String? = 56 | "The key can no longer be used. Check if a new fingerprint is enrolled or the secure lock is disabled.", 57 | cause: Throwable? = null 58 | ) : AuthenticationException(message, cause) 59 | } 60 | class SecureExecutionException( 61 | message: String? = null, 62 | cause: Throwable? = null 63 | ) : WebAuthnException(message, cause) 64 | class KeyNotFoundException(message: String? = null, cause: Throwable? = null) : WebAuthnException(message, cause) 65 | class UnknownException(message: String, cause: Throwable? = null) : WebAuthnException(message, cause) 66 | class UtilityException(message: String, cause: Throwable? = null) : WebAuthnException(message, cause) 67 | class EncodingException(message: String, cause: Throwable? = null) : WebAuthnException(message, cause) 68 | 69 | /** 70 | * Error occurs when an exception is raised during the FIDO2 operation, 71 | * triggering the deletion of intermediate data, 72 | * but an issue arises during the deletion process. 73 | * 74 | * @param message The error message. 75 | * @param cause The cause of the issue during the deletion process. 76 | * @param trigger The exception that triggered the deletion. 77 | */ 78 | class DeletionException( 79 | message: String, 80 | cause: Throwable? = null, 81 | trigger: Throwable? = null 82 | ) : WebAuthnException(message, cause) 83 | } 84 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/handler/AuthenticationHandler.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.handler 18 | 19 | import android.content.Context 20 | import androidx.fragment.app.FragmentActivity 21 | import java.security.Signature 22 | import jp.co.lycorp.webauthn.model.Fido2PromptInfo 23 | import jp.co.lycorp.webauthn.model.Fido2UserAuthResult 24 | 25 | /** 26 | * Interface for handling authentication operations in a WebAuthn context. 27 | * Provides methods to check support for authentication and to perform authentication. 28 | */ 29 | interface AuthenticationHandler { 30 | 31 | class AuthenticationFailedException(val errorCode: Int? = null, message: String? = null, cause: Throwable? = null) : 32 | Exception(message, cause) 33 | class AuthenticationErrorException(val errorCode: Int? = null, message: String? = null, cause: Throwable? = null) : 34 | Exception(message, cause) 35 | 36 | /** 37 | * Checks if the current device or environment supports the required authentication methods. 38 | * 39 | * @param context The activity context used for UI operations. 40 | * @return True if the authentication method is supported, false otherwise. 41 | */ 42 | fun isSupported(context: Context): Boolean 43 | 44 | /** 45 | * Performs user authentication, optionally using a provided signature and prompt information. 46 | * 47 | * @param activity The activity context used for UI operations. 48 | * @param fido2PromptInfo The prompt information for FIDO2 authentication, if any. 49 | * @param signatureProvider A function that provides a signature for the authentication process. 50 | * @return The result of the user authentication, encapsulated in a Fido2UserAuthResult object. 51 | * @throws WebAuthnException If an error occurs during the authentication process. 52 | */ 53 | suspend fun authenticate( 54 | activity: FragmentActivity, 55 | fido2PromptInfo: Fido2PromptInfo?, 56 | signatureProvider: (() -> Signature)? = null 57 | ): Fido2UserAuthResult 58 | } 59 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/handler/BiometricAuthenticationHandler.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.handler 18 | 19 | import android.content.Context 20 | import androidx.biometric.BiometricManager 21 | import androidx.biometric.BiometricPrompt 22 | import androidx.core.content.ContextCompat 23 | import androidx.fragment.app.FragmentActivity 24 | import java.security.Signature 25 | import jp.co.lycorp.webauthn.model.Fido2PromptInfo 26 | import jp.co.lycorp.webauthn.model.Fido2UserAuthResult 27 | import kotlin.coroutines.resumeWithException 28 | import kotlinx.coroutines.CoroutineDispatcher 29 | import kotlinx.coroutines.Dispatchers 30 | import kotlinx.coroutines.suspendCancellableCoroutine 31 | import kotlinx.coroutines.withContext 32 | 33 | internal class BiometricAuthenticationHandler( 34 | private val authHandlerDispatcher: CoroutineDispatcher = Dispatchers.Main, 35 | ) : AuthenticationHandler { 36 | override fun isSupported(context: Context): Boolean { 37 | val biometricManager = BiometricManager.from(context) 38 | return biometricManager.canAuthenticate( 39 | BiometricManager.Authenticators.BIOMETRIC_STRONG 40 | ) == BiometricManager.BIOMETRIC_SUCCESS 41 | } 42 | 43 | override suspend fun authenticate( 44 | activity: FragmentActivity, 45 | fido2PromptInfo: Fido2PromptInfo?, 46 | signatureProvider: (() -> Signature)? 47 | ): Fido2UserAuthResult { 48 | return authenticateUserWithBiometricPrompt(activity, fido2PromptInfo, signatureProvider) 49 | } 50 | 51 | private suspend fun authenticateUserWithBiometricPrompt( 52 | activity: FragmentActivity, 53 | fido2PromptInfo: Fido2PromptInfo?, 54 | signatureProvider: (() -> Signature)? 55 | ): Fido2UserAuthResult = withContext(authHandlerDispatcher) { 56 | suspendCancellableCoroutine { continuation -> 57 | val promptInfo = 58 | BiometricPrompt.PromptInfo.Builder() 59 | .setTitle(fido2PromptInfo?.title ?: "Biometric Authentication") 60 | .setSubtitle(fido2PromptInfo?.subtitle ?: "Enter biometric credentials to proceed") 61 | .setDescription( 62 | fido2PromptInfo?.description 63 | ?: "Input your Fingerprint or FaceID to ensure it's you!", 64 | ) 65 | .setNegativeButtonText(fido2PromptInfo?.negativeButtonText ?: "Cancel") 66 | .build() 67 | 68 | val biometricPrompt = 69 | BiometricPrompt( 70 | activity, 71 | ContextCompat.getMainExecutor(activity.applicationContext), 72 | object : BiometricPrompt.AuthenticationCallback() { 73 | override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { 74 | if (continuation.isActive) { 75 | continuation.resumeWith( 76 | Result.success( 77 | Fido2UserAuthResult( 78 | signature = result.cryptoObject?.signature 79 | ) 80 | ) 81 | ) 82 | } 83 | } 84 | 85 | override fun onAuthenticationFailed() { 86 | // In the event of an authentication failure, the user is allowed to try again. 87 | } 88 | 89 | override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { 90 | if (continuation.isActive) { 91 | continuation.resumeWithException( 92 | AuthenticationHandler.AuthenticationErrorException( 93 | errorCode = errorCode, 94 | message = "Biometric authentication error: $errString" 95 | ) 96 | ) 97 | } 98 | } 99 | }, 100 | ) 101 | 102 | continuation.invokeOnCancellation { 103 | biometricPrompt.cancelAuthentication() 104 | } 105 | 106 | if (signatureProvider != null) { 107 | val cryptoObject = BiometricPrompt.CryptoObject(signatureProvider()) 108 | biometricPrompt.authenticate(promptInfo, cryptoObject) 109 | } else { 110 | biometricPrompt.authenticate(promptInfo) 111 | } 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/handler/DeviceCredentialAuthenticationHandler.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.handler 18 | 19 | import android.content.Context 20 | import android.os.Build 21 | import androidx.biometric.BiometricManager 22 | import androidx.biometric.BiometricPrompt 23 | import androidx.core.content.ContextCompat 24 | import androidx.fragment.app.FragmentActivity 25 | import java.security.Signature 26 | import jp.co.lycorp.webauthn.model.Fido2PromptInfo 27 | import jp.co.lycorp.webauthn.model.Fido2UserAuthResult 28 | import kotlin.coroutines.resumeWithException 29 | import kotlinx.coroutines.CoroutineDispatcher 30 | import kotlinx.coroutines.Dispatchers 31 | import kotlinx.coroutines.suspendCancellableCoroutine 32 | import kotlinx.coroutines.withContext 33 | 34 | internal class DeviceCredentialAuthenticationHandler( 35 | private val authHandlerDispatcher: CoroutineDispatcher = Dispatchers.Main, 36 | ) : AuthenticationHandler { 37 | 38 | private val keyguardManagerWrapper = KeyguardManagerWrapper() 39 | 40 | override fun isSupported(context: Context): Boolean { 41 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 42 | // API level >= 30 43 | val biometricManager = BiometricManager.from(context) 44 | biometricManager.canAuthenticate( 45 | BiometricManager.Authenticators.BIOMETRIC_STRONG or 46 | BiometricManager.Authenticators.DEVICE_CREDENTIAL 47 | ) == BiometricManager.BIOMETRIC_SUCCESS 48 | } else { 49 | // API level < 30 50 | keyguardManagerWrapper.isSupported(context) 51 | } 52 | } 53 | 54 | override suspend fun authenticate( 55 | activity: FragmentActivity, 56 | fido2PromptInfo: Fido2PromptInfo?, 57 | signatureProvider: (() -> Signature)? 58 | ): Fido2UserAuthResult { 59 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 60 | authenticateUserWithBiometricPrompt(activity, fido2PromptInfo, signatureProvider) 61 | } else { 62 | authenticateUserWithKeyguardManager(activity, fido2PromptInfo, signatureProvider) 63 | } 64 | } 65 | 66 | private suspend fun authenticateUserWithBiometricPrompt( 67 | activity: FragmentActivity, 68 | fido2PromptInfo: Fido2PromptInfo?, 69 | signatureProvider: (() -> Signature)? 70 | ): Fido2UserAuthResult = withContext(authHandlerDispatcher) { 71 | suspendCancellableCoroutine { continuation -> 72 | val promptInfo = 73 | BiometricPrompt.PromptInfo.Builder() 74 | .setTitle(fido2PromptInfo?.title ?: "Device Credential Authentication") 75 | .setSubtitle(fido2PromptInfo?.subtitle ?: "Enter device credentials to proceed") 76 | .setDescription( 77 | fido2PromptInfo?.description 78 | ?: "Input your Fingerprint or device credential to ensure it's you!", 79 | ) 80 | .setAllowedAuthenticators( 81 | BiometricManager.Authenticators.BIOMETRIC_STRONG or 82 | BiometricManager.Authenticators.DEVICE_CREDENTIAL 83 | ) 84 | .build() 85 | 86 | val biometricPrompt = 87 | BiometricPrompt( 88 | activity, 89 | ContextCompat.getMainExecutor(activity.applicationContext), 90 | object : BiometricPrompt.AuthenticationCallback() { 91 | override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { 92 | continuation.resumeWith( 93 | Result.success( 94 | Fido2UserAuthResult( 95 | signature = result.cryptoObject?.signature 96 | ) 97 | ) 98 | ) 99 | } 100 | 101 | override fun onAuthenticationFailed() { 102 | // In the event of an authentication failure, the user is allowed to try again. 103 | } 104 | 105 | override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { 106 | continuation.resumeWithException( 107 | AuthenticationHandler.AuthenticationErrorException( 108 | errorCode, 109 | "Biometric authentication error: $errString" 110 | ) 111 | ) 112 | } 113 | }, 114 | ) 115 | 116 | continuation.invokeOnCancellation { 117 | biometricPrompt.cancelAuthentication() 118 | } 119 | 120 | if (signatureProvider != null) { 121 | val cryptoObject = BiometricPrompt.CryptoObject(signatureProvider()) 122 | biometricPrompt.authenticate(promptInfo, cryptoObject) 123 | } else { 124 | biometricPrompt.authenticate(promptInfo) 125 | } 126 | } 127 | } 128 | 129 | private suspend fun authenticateUserWithKeyguardManager( 130 | activity: FragmentActivity, 131 | fido2PromptInfo: Fido2PromptInfo?, 132 | signatureProvider: (() -> Signature)? 133 | ): Fido2UserAuthResult = withContext(authHandlerDispatcher) { 134 | try { 135 | keyguardManagerWrapper.authenticate(activity, fido2PromptInfo) 136 | val signature = signatureProvider?.invoke() 137 | return@withContext Fido2UserAuthResult(signature = signature) 138 | } catch (e: KeyguardManagerWrapper.KeyguardNotSecuredException) { 139 | throw AuthenticationHandler.AuthenticationErrorException( 140 | message = "Keyguard not secured", 141 | cause = e 142 | ) 143 | } catch (e: KeyguardManagerWrapper.DeviceCredentialIntentNotAvailableException) { 144 | throw AuthenticationHandler.AuthenticationErrorException( 145 | message = "Device credential intent not available", 146 | cause = e 147 | ) 148 | } catch (e: KeyguardManagerWrapper.KeyguardManagerAuthenticationFailedException) { 149 | throw AuthenticationHandler.AuthenticationErrorException( 150 | errorCode = e.errorCode, 151 | message = e.message, 152 | cause = e 153 | ) 154 | } catch (e: Exception) { 155 | throw AuthenticationHandler.AuthenticationErrorException( 156 | message = "An unexpected error occurred", 157 | cause = e 158 | ) 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/handler/KeyguardManagerWrapper.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.handler 18 | 19 | import android.app.KeyguardManager 20 | import android.content.Context 21 | import android.content.Intent 22 | import android.hardware.biometrics.BiometricPrompt 23 | import android.os.Bundle 24 | import android.util.Log 25 | import androidx.appcompat.app.AppCompatActivity 26 | import jp.co.lycorp.webauthn.model.Fido2PromptInfo 27 | import kotlin.coroutines.resume 28 | import kotlin.coroutines.resumeWithException 29 | import kotlinx.coroutines.suspendCancellableCoroutine 30 | 31 | class KeyguardManagerWrapper { 32 | 33 | class KeyguardNotSecuredException(message: String) : Exception(message) 34 | class DeviceCredentialIntentNotAvailableException(message: String) : Exception(message) 35 | class KeyguardManagerAuthenticationFailedException(val errorCode: Int?, message: String) : Exception(message) 36 | 37 | fun isSupported(context: Context): Boolean { 38 | val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager 39 | return keyguardManager.isDeviceSecure 40 | } 41 | 42 | suspend fun authenticate(context: Context, fido2PromptInfo: Fido2PromptInfo?): Boolean { 43 | val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager 44 | 45 | if (!keyguardManager.isKeyguardSecure) { 46 | throw KeyguardNotSecuredException("Keyguard not secured") 47 | } 48 | 49 | val intent = keyguardManager.createConfirmDeviceCredentialIntent( 50 | fido2PromptInfo?.title ?: "Device Credential Authentication", 51 | fido2PromptInfo?.description ?: "Input your Fingerprint or device credential to ensure it's you!" 52 | ) ?: throw DeviceCredentialIntentNotAvailableException("Device credential intent not available") 53 | 54 | Log.d("KeyguardManagerWrapper", "Starting AuthenticationActivity with intent") 55 | 56 | return suspendCancellableCoroutine { continuation -> 57 | AuthenticationActivity.start(context, intent) { result, errorCode -> 58 | if (result) { 59 | Log.d("KeyguardManagerWrapper", "Authentication succeeded") 60 | continuation.resume(true) 61 | } else { 62 | Log.d("KeyguardManagerWrapper", "Authentication failed") 63 | continuation.resumeWithException( 64 | KeyguardManagerAuthenticationFailedException( 65 | errorCode = errorCode, 66 | message = "Authentication failed with errorCode: $errorCode" 67 | ) 68 | ) 69 | } 70 | } 71 | } 72 | } 73 | 74 | class AuthenticationActivity : AppCompatActivity() { 75 | 76 | companion object { 77 | private const val REQUEST_CODE_CONFIRM_DEVICE_CREDENTIAL = 1 78 | private var callback: ((Boolean, Int?) -> Unit)? = null 79 | 80 | fun start(context: Context, intent: Intent, callback: (Boolean, Int?) -> Unit) { 81 | this.callback = callback 82 | val activityIntent = Intent(context, AuthenticationActivity::class.java).apply { 83 | putExtra("fido2_auth_intent", intent) 84 | addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 85 | } 86 | Log.d("AuthenticationActivity", "Starting activity with intent") 87 | context.startActivity(activityIntent) 88 | } 89 | } 90 | 91 | override fun onCreate(savedInstanceState: Bundle?) { 92 | super.onCreate(savedInstanceState) 93 | val intent = intent.getParcelableExtra("fido2_auth_intent") 94 | if (intent != null) { 95 | Log.d("AuthenticationActivity", "Starting activity for result") 96 | startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIAL) 97 | } else { 98 | Log.d("AuthenticationActivity", "Intent is null, finishing activity") 99 | callback?.invoke(false, BiometricPrompt.BIOMETRIC_ERROR_UNABLE_TO_PROCESS) 100 | finish() 101 | } 102 | } 103 | 104 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 105 | super.onActivityResult(requestCode, resultCode, data) 106 | if (requestCode == REQUEST_CODE_CONFIRM_DEVICE_CREDENTIAL) { 107 | Log.d("AuthenticationActivity", "Received result: $resultCode") 108 | when (resultCode) { 109 | RESULT_OK -> { 110 | callback?.invoke(true, null) 111 | Log.d("AuthenticationActivity", "Authentication succeeded") 112 | } 113 | RESULT_CANCELED -> { 114 | Log.d("AuthenticationActivity", "Authentication canceled") 115 | callback?.invoke(false, BiometricPrompt.BIOMETRIC_ERROR_USER_CANCELED) 116 | } 117 | else -> { 118 | Log.d("AuthenticationActivity", "Authentication failed") 119 | callback?.invoke(false, BiometricPrompt.BIOMETRIC_ERROR_UNABLE_TO_PROCESS) 120 | } 121 | } 122 | } 123 | finish() 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AssertionObject.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import co.nstant.`in`.cbor.builder.AbstractBuilder 20 | import co.nstant.`in`.cbor.builder.MapBuilder 21 | 22 | class AssertionObject( 23 | val authenticatorData: ByteArray, 24 | val signature: ByteArray, 25 | ) : CborSerializable { 26 | override fun ?> toCBOR(builder: MapBuilder): T { 27 | return builder 28 | .put("authenticatorData", this.authenticatorData) 29 | .put("signature", this.signature) 30 | .end() 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AttestationConveyancePreference.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | enum class AttestationConveyancePreference(val value: String) { 20 | NONE("none"), 21 | INDIRECT("indirect"), 22 | DIRECT("direct"), 23 | ; 24 | 25 | companion object { 26 | fun fromValue(value: String): AttestationConveyancePreference? { 27 | return AttestationConveyancePreference.values().find { it.value == value } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AttestationObject.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import co.nstant.`in`.cbor.builder.AbstractBuilder 20 | import co.nstant.`in`.cbor.builder.MapBuilder 21 | 22 | /** 23 | * Represents an Attestation Object in the WebAuthn process. 24 | * 25 | * This class corresponds to the attestation object as defined in the Web Authentication: An API for accessing Public Key Credentials Level 2 specification. 26 | * For more details, see the specification: [Web Authentication: Level 2 - Attestation Object](https://www.w3.org/TR/webauthn-2/#attestation-object) 27 | * 28 | * AttestationObject: 29 | * | authData | fmt | attStmt | 30 | * |--------------|------|-----------| 31 | * | variable size| text | map-based | 32 | */ 33 | data class AttestationObject( 34 | val authData: ByteArray, 35 | val fmt: String, 36 | val attStmt: AttestationStatement, 37 | ) : CborSerializable { 38 | override fun ?> toCBOR(builder: MapBuilder): T { 39 | builder.put("authData", authData) 40 | builder.put("fmt", fmt) 41 | if (fmt == AttestationStatementFormat.NONE.value) { 42 | builder.putMap("attStmt") 43 | } else { 44 | attStmt.toCBOR(builder.startMap("attStmt")) 45 | } 46 | return builder.end() 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AttestationStatement.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import android.security.keystore.KeyProperties 20 | import co.nstant.`in`.cbor.builder.AbstractBuilder 21 | import co.nstant.`in`.cbor.builder.MapBuilder 22 | import java.security.spec.AlgorithmParameterSpec 23 | import java.security.spec.ECGenParameterSpec 24 | 25 | interface AttestationStatement : CborSerializable { 26 | override fun ?> toCBOR(builder: MapBuilder): T 27 | } 28 | 29 | class AndroidKeyAttestationStatement( 30 | val alg: Long, 31 | val sig: ByteArray, 32 | val x5c: List 33 | ) : AttestationStatement { 34 | override fun ?> toCBOR(builder: MapBuilder): T { 35 | return builder 36 | .put("alg", alg) 37 | .put("sig", sig) 38 | .putArray("x5c").also { 39 | for (i in x5c) { 40 | it.add(i) 41 | } 42 | } 43 | .end() 44 | .end() 45 | } 46 | } 47 | 48 | class NoneAttestationStatement : AttestationStatement { 49 | override fun ?> toCBOR(builder: MapBuilder): T { 50 | return builder.end() 51 | } 52 | } 53 | 54 | enum class AttestationStatementFormat(val value: String) { 55 | ANDROID_KEY("android-key"), 56 | NONE("none"), 57 | } 58 | 59 | enum class COSEAlgorithmIdentifier(val value: Long) { 60 | RS1(-65535), // RSASSA-PKCS1-v1_5 with SHA-1 61 | RS256(-257), // RSASSA-PKCS1-v1_5 with SHA-256 62 | RS384(-258), // RSASSA-PKCS1-v1_5 with SHA-384 63 | RS512(-259), // RSASSA-PKCS1-v1_5 with SHA-512 64 | PS256(-37), // RSASSA-PSS with SHA-256 65 | PS384(-38), // RSASSA-PSS with SHA-384 66 | PS512(-39), // RSASSA-PSS with SHA-512 67 | EdDSA(-8), // EdDSA 68 | ES256(-7), // ECDSA with SHA-256 69 | ES384(-35), // ECDSA with SHA-384 70 | ES512(-36), // ECDSA with SHA-512 71 | ES256K(-43), // ECDSA using P-256K and SHA-256 72 | ; 73 | 74 | companion object { 75 | fun fromValue(value: Long): COSEAlgorithmIdentifier? { 76 | return COSEAlgorithmIdentifier.entries.find { it.value == value } 77 | } 78 | } 79 | } 80 | fun COSEAlgorithmIdentifier.getSignatureAlgorithmName(): String? { 81 | val correspondingSignatureAlgorithm = SignatureAlgorithms.entries.find { it.name == this.name } 82 | return correspondingSignatureAlgorithm?.algName 83 | } 84 | 85 | fun COSEAlgorithmIdentifier.getDigests(): String? { 86 | return when (this) { 87 | COSEAlgorithmIdentifier.RS1 -> KeyProperties.DIGEST_SHA1 88 | COSEAlgorithmIdentifier.RS256 -> KeyProperties.DIGEST_SHA256 89 | COSEAlgorithmIdentifier.RS384 -> KeyProperties.DIGEST_SHA384 90 | COSEAlgorithmIdentifier.RS512 -> KeyProperties.DIGEST_SHA512 91 | COSEAlgorithmIdentifier.PS256 -> KeyProperties.DIGEST_SHA256 92 | COSEAlgorithmIdentifier.PS384 -> KeyProperties.DIGEST_SHA384 93 | COSEAlgorithmIdentifier.PS512 -> KeyProperties.DIGEST_SHA512 94 | COSEAlgorithmIdentifier.EdDSA -> KeyProperties.DIGEST_SHA512 95 | COSEAlgorithmIdentifier.ES256 -> KeyProperties.DIGEST_SHA256 96 | COSEAlgorithmIdentifier.ES384 -> KeyProperties.DIGEST_SHA384 97 | COSEAlgorithmIdentifier.ES512 -> KeyProperties.DIGEST_SHA512 98 | COSEAlgorithmIdentifier.ES256K -> KeyProperties.DIGEST_SHA256 99 | } 100 | } 101 | 102 | fun COSEAlgorithmIdentifier.getSignaturePaddings(): String? { 103 | return when (this) { 104 | COSEAlgorithmIdentifier.RS1 -> KeyProperties.SIGNATURE_PADDING_RSA_PKCS1 105 | COSEAlgorithmIdentifier.RS256 -> KeyProperties.SIGNATURE_PADDING_RSA_PKCS1 106 | COSEAlgorithmIdentifier.RS384 -> KeyProperties.SIGNATURE_PADDING_RSA_PKCS1 107 | COSEAlgorithmIdentifier.RS512 -> KeyProperties.SIGNATURE_PADDING_RSA_PKCS1 108 | COSEAlgorithmIdentifier.PS256 -> KeyProperties.SIGNATURE_PADDING_RSA_PSS 109 | COSEAlgorithmIdentifier.PS384 -> KeyProperties.SIGNATURE_PADDING_RSA_PSS 110 | COSEAlgorithmIdentifier.PS512 -> KeyProperties.SIGNATURE_PADDING_RSA_PSS 111 | COSEAlgorithmIdentifier.EdDSA -> null 112 | COSEAlgorithmIdentifier.ES256 -> null 113 | COSEAlgorithmIdentifier.ES384 -> null 114 | COSEAlgorithmIdentifier.ES512 -> null 115 | COSEAlgorithmIdentifier.ES256K -> null 116 | } 117 | } 118 | 119 | fun COSEAlgorithmIdentifier.getAlgorithmParameterSpec(): AlgorithmParameterSpec? { 120 | return when (this) { 121 | COSEAlgorithmIdentifier.RS1 -> null 122 | COSEAlgorithmIdentifier.RS256 -> null 123 | COSEAlgorithmIdentifier.RS384 -> null 124 | COSEAlgorithmIdentifier.RS512 -> null 125 | COSEAlgorithmIdentifier.PS256 -> null 126 | COSEAlgorithmIdentifier.PS384 -> null 127 | COSEAlgorithmIdentifier.PS512 -> null 128 | COSEAlgorithmIdentifier.EdDSA -> null 129 | COSEAlgorithmIdentifier.ES256 -> ECGenParameterSpec("secp256r1") 130 | COSEAlgorithmIdentifier.ES384 -> ECGenParameterSpec("secp384r1") 131 | COSEAlgorithmIdentifier.ES512 -> ECGenParameterSpec("secp512r1") 132 | COSEAlgorithmIdentifier.ES256K -> ECGenParameterSpec("secp256k1") 133 | } 134 | } 135 | 136 | fun COSEAlgorithmIdentifier.getKeyProperties(): String? { 137 | return when (this) { 138 | COSEAlgorithmIdentifier.RS1 -> KeyProperties.KEY_ALGORITHM_RSA 139 | COSEAlgorithmIdentifier.RS256 -> KeyProperties.KEY_ALGORITHM_RSA 140 | COSEAlgorithmIdentifier.RS384 -> KeyProperties.KEY_ALGORITHM_RSA 141 | COSEAlgorithmIdentifier.RS512 -> KeyProperties.KEY_ALGORITHM_RSA 142 | COSEAlgorithmIdentifier.PS256 -> KeyProperties.KEY_ALGORITHM_RSA 143 | COSEAlgorithmIdentifier.PS384 -> KeyProperties.KEY_ALGORITHM_RSA 144 | COSEAlgorithmIdentifier.PS512 -> KeyProperties.KEY_ALGORITHM_RSA 145 | COSEAlgorithmIdentifier.EdDSA -> KeyProperties.KEY_ALGORITHM_EC 146 | COSEAlgorithmIdentifier.ES256 -> KeyProperties.KEY_ALGORITHM_EC 147 | COSEAlgorithmIdentifier.ES384 -> KeyProperties.KEY_ALGORITHM_EC 148 | COSEAlgorithmIdentifier.ES512 -> KeyProperties.KEY_ALGORITHM_EC 149 | COSEAlgorithmIdentifier.ES256K -> KeyProperties.KEY_ALGORITHM_EC 150 | } 151 | } 152 | 153 | enum class SignatureAlgorithms(val algName: String) { 154 | RS1("SHA1withRSA"), 155 | RS256("SHA256withRSA"), 156 | RS384("SHA384withRSA"), 157 | RS512("SHA512withRSA"), 158 | PS256("SHA256withRSA/PSS"), 159 | PS384("SHA384withRSA/PSS"), 160 | PS512("SHA512withRSA/PSS"), 161 | EdDSA("EdDSA"), 162 | ES256("SHA256withECDSA"), 163 | ES384("SHA384withECDSA"), 164 | ES512("SHA512withECDSA"), 165 | ES256K("SHA256withECDSAinP256K"), 166 | } 167 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticationExtensions.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import co.nstant.`in`.cbor.builder.AbstractBuilder 20 | import co.nstant.`in`.cbor.builder.MapBuilder 21 | 22 | // NOTE: This file contains several dummy methods and classes. 23 | // These are made to support authenticator extensions if they are needed in the future. 24 | // If an authenticator extension is required, the following interfaces and methods should be properly implemented. 25 | 26 | // AuthenticatorExtensionInput is not currently implemented. (Therefore, it is always treated as null in code now.) 27 | interface AuthenticatorExtensionsInput : CborSerializable { 28 | override fun ?> toCBOR(builder: MapBuilder): T 29 | } 30 | 31 | class AuthenticatorExtensionsOutput : CborSerializable { 32 | companion object { 33 | fun getAuthenticatorExtensionResult( 34 | authenticatorExtensionsInput: AuthenticatorExtensionsInput? = null, 35 | ): AuthenticatorExtensionsOutput? { 36 | // Need to be implemented when authenticator extension is used. 37 | return null 38 | } 39 | } 40 | 41 | override fun ?> toCBOR(builder: MapBuilder): T { 42 | // Need to be implemented when authenticator extension is used. 43 | return builder.end() 44 | } 45 | } 46 | 47 | class ClientExtensionInput { 48 | 49 | fun processAuthenticatorExtensionsInput(): AuthenticatorExtensionsInput? { 50 | // Need to be implemented when authenticator extension is used. 51 | return null 52 | } 53 | 54 | fun processClientExtensionsOutput(): ClientExtensionsOutput { 55 | // Need to be implemented when client extension is used. 56 | return ClientExtensionsOutput() 57 | } 58 | } 59 | 60 | class ClientExtensionsOutput 61 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticationMethod.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | enum class AuthenticationMethod(val value: String) { 20 | Biometric("Biometric"), 21 | DeviceCredential("DeviceCredential") 22 | ; 23 | 24 | companion object { 25 | fun fromValue(value: String): AuthenticationMethod? { 26 | return AuthenticationMethod.values().find { it.value == value } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticatorAttachment.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | enum class AuthenticatorAttachment(val value: String) { 20 | PLATFORM("platform"), 21 | CROSS_PLATFORM("cross-platform"), 22 | ; 23 | 24 | companion object { 25 | fun fromValue(value: String): AuthenticatorAttachment? { 26 | return AuthenticatorAttachment.values().find { it.name == value } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticatorData.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import co.nstant.`in`.cbor.builder.AbstractBuilder 20 | import co.nstant.`in`.cbor.builder.MapBuilder 21 | import java.nio.ByteBuffer 22 | import java.security.interfaces.ECPublicKey 23 | import jp.co.lycorp.webauthn.exceptions.WebAuthnException 24 | 25 | /** 26 | * Represents Authenticator Data in the WebAuthn process. 27 | * 28 | * This class corresponds to the authenticator data as defined in the Web Authentication: An API for accessing Public Key Credentials Level 2 specification. 29 | * For more details, see the specification: [Web Authentication: Level 2 - Authenticator Data](https://www.w3.org/TR/webauthn-2/#authenticator-data) 30 | * 31 | * AuthenticatorData: 32 | * | rpIdHash | flags | signCount | attestedCredData | extensions | 33 | * |----------|---------|-----------|------------------|---------------| 34 | * | 32 bytes | 1 byte | 4 bytes | variable size | variable size | 35 | */ 36 | data class AuthenticatorData( 37 | val rpIdHash: ByteArray, 38 | var flags: UByte, 39 | val signCount: UInt, 40 | val attestedCredData: ByteArray? = null, 41 | val extensions: ByteArray? = null, 42 | ) { 43 | fun toByteArray(): ByteArray { 44 | if (attestedCredData != null) { 45 | val atFlag = AuthenticatorDataFlags.AT.value 46 | flags = flags or atFlag 47 | } 48 | if (extensions != null) { 49 | val edFlag = AuthenticatorDataFlags.ED.value 50 | flags = flags or edFlag 51 | } 52 | 53 | try { 54 | return ByteBuffer.allocate( 55 | rpIdHash.size + 56 | 1 + 57 | 4 + 58 | (attestedCredData?.size ?: 0) + 59 | (extensions?.size ?: 0), 60 | ).apply { 61 | put(rpIdHash) 62 | put(flags.toByte()) 63 | putInt(signCount.toInt()) 64 | attestedCredData?.let { put(it) } 65 | extensions?.let { put(it) } 66 | }.array() 67 | } catch (e: Exception) { 68 | throw WebAuthnException.EncodingException("Cannot convert AuthenticatorData to ByteArray", e) 69 | } 70 | } 71 | } 72 | 73 | /** 74 | * Represents Attested Credential Data in the WebAuthn process. 75 | * 76 | * This class corresponds to the attested credential data as defined in the Web Authentication: An API for accessing Public Key Credentials Level 2 specification. 77 | * For more details, see the specification: [Web Authentication: Level 2 - Attested Credential Data](https://www.w3.org/TR/webauthn-2/#attested-credential-data) 78 | * 79 | * AttestedCredentialData: 80 | * | aaguid | credIdLength | credID | publicKey | 81 | * |----------|--------------|-----------------|---------------| 82 | * | 16 bytes | 2 bytes | credID.length() | variable size | 83 | */ 84 | class AttestedCredData( 85 | val aaguid: ByteArray, 86 | val credId: ByteArray, 87 | val publicKey: ByteArray, 88 | ) { 89 | fun toByteArray(): ByteArray { 90 | try { 91 | return ByteBuffer.allocate(aaguid.size + 2 + credId.size + publicKey.size).apply { 92 | put(aaguid) 93 | putShort(credId.size.toShort()) 94 | put(credId) 95 | put(publicKey) 96 | }.array() 97 | } catch (e: Exception) { 98 | throw WebAuthnException.EncodingException("Cannot convert AttestedCredData to ByteArray", e) 99 | } 100 | } 101 | } 102 | 103 | class EC2COSEKey( 104 | var kty: Int, 105 | var alg: Int, 106 | var crv: Int, 107 | var x: ByteArray, 108 | var y: ByteArray, 109 | ) : CborSerializable { 110 | constructor(ecPublicKey: ECPublicKey) : this( 111 | kty = 2, 112 | alg = -7, 113 | crv = 1, 114 | x = ecPublicKey.w.affineX.toByteArray(), 115 | y = ecPublicKey.w.affineY.toByteArray(), 116 | ) 117 | 118 | override fun ?> toCBOR(builder: MapBuilder): T { 119 | return builder 120 | .put(1, kty.toLong()) 121 | .put(3, alg.toLong()) 122 | .put(-1, crv.toLong()) 123 | .put(-2, x) 124 | .put(-3, y) 125 | .end() 126 | } 127 | } 128 | 129 | enum class AuthenticatorDataFlags(val value: UByte) { 130 | UP(0b0000_0001u), 131 | UV(0b0000_0100u), 132 | AT(0b0100_0000u), 133 | ED(0b1000_0000u), 134 | ; 135 | 136 | companion object { 137 | fun makeFlags( 138 | userPresent: Boolean = false, 139 | userVerified: Boolean = false, 140 | attestedCredentialDataIncluded: Boolean = false, 141 | extensionDataIncluded: Boolean = false, 142 | ): UByte { 143 | var flags: UByte = 0u 144 | if (userPresent) flags = flags or UP.value 145 | if (userVerified) flags = flags or UV.value 146 | if (attestedCredentialDataIncluded) flags = flags or AT.value 147 | if (extensionDataIncluded) flags = flags or ED.value 148 | return flags 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticatorGetAssertionResult.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | data class AuthenticatorGetAssertionResult( 20 | val credentialId: ByteArray, 21 | val authenticatorData: ByteArray, 22 | val signature: ByteArray, 23 | val userHandle: ByteArray?, 24 | ) 25 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticatorMakeCredentialResult.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | data class AuthenticatorMakeCredentialResult( 20 | val credentialId: ByteArray, 21 | val attestationObject: ByteArray, 22 | ) 23 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticatorResponse.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | interface AuthenticatorResponse { 20 | val clientDataJSON: ByteArray 21 | } 22 | 23 | class AuthenticatorAttestationResponse( 24 | override val clientDataJSON: ByteArray, 25 | val attestationObject: ByteArray, 26 | ) : jp.co.lycorp.webauthn.model.AuthenticatorResponse 27 | 28 | class AuthenticatorAssertionResponse( 29 | val authenticatorData: ByteArray, 30 | val signature: ByteArray, 31 | val userHandle: ByteArray?, 32 | override val clientDataJSON: ByteArray, 33 | ) : jp.co.lycorp.webauthn.model.AuthenticatorResponse 34 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticatorSelectionCriteria.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | data class AuthenticatorSelectionCriteria( 20 | val authenticatorAttachment: String?, 21 | val userVerification: String = UserVerificationRequirement.PREFERRED.value, 22 | ) 23 | 24 | enum class UserVerificationRequirement(val value: String) { 25 | REQUIRED("required"), 26 | PREFERRED("preferred"), 27 | ; 28 | 29 | companion object { 30 | fun fromValue(value: String): UserVerificationRequirement? { 31 | return UserVerificationRequirement.values().find { it.value == value } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticatorTransport.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | enum class AuthenticatorTransport(val value: String) { 20 | BLE("ble"), 21 | INTERNAL("internal"), 22 | ; 23 | 24 | companion object { 25 | fun fromValue(value: String): AuthenticatorTransport? { 26 | return AuthenticatorTransport.values().find { it.value == value } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/AuthenticatorType.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import java.nio.ByteBuffer 20 | import java.nio.ByteOrder 21 | import java.util.UUID 22 | 23 | enum class AuthenticatorType(val authenticatorName: String, val aaguid: UUID) { 24 | BiometricNone("BiometricNone", UUID.fromString("fca28135-9915-4c70-de30-56de200fd2cb")), 25 | BiometricAndroidKey("BiometricAndroidKey", UUID.fromString("8c120a4d-52b3-99ef-eaf6-7cfb2a3e3f89")), 26 | DeviceCredentialNone("DeviceCredentialNone", UUID.fromString("616fcfb7-8fe1-4b6a-ec90-5db1424a9b36")), 27 | DeviceCredentialAndroidKey("DeviceCredentialAndroidKey", UUID.fromString("2b7a96a3-f571-ee4c-632c-c5458dfadfe3")), 28 | ; 29 | 30 | fun aaguidBytes(): ByteArray { 31 | return ByteBuffer.wrap(ByteArray(16)).apply { 32 | order(ByteOrder.BIG_ENDIAN) 33 | putLong(aaguid.mostSignificantBits) 34 | putLong(aaguid.leastSignificantBits) 35 | }.array() 36 | } 37 | 38 | fun getAuthenticationMethod(): AuthenticationMethod { 39 | return when (this) { 40 | BiometricNone -> AuthenticationMethod.Biometric 41 | BiometricAndroidKey -> AuthenticationMethod.Biometric 42 | DeviceCredentialNone -> AuthenticationMethod.DeviceCredential 43 | DeviceCredentialAndroidKey -> AuthenticationMethod.DeviceCredential 44 | } 45 | } 46 | 47 | fun getAttestationStatementFormat(): AttestationStatementFormat { 48 | return when (this) { 49 | BiometricNone -> AttestationStatementFormat.NONE 50 | BiometricAndroidKey -> AttestationStatementFormat.ANDROID_KEY 51 | DeviceCredentialNone -> AttestationStatementFormat.NONE 52 | DeviceCredentialAndroidKey -> AttestationStatementFormat.ANDROID_KEY 53 | } 54 | } 55 | 56 | companion object { 57 | fun getAuthenticatorType( 58 | authenticationMethod: AuthenticationMethod, 59 | attestationStatementFormat: AttestationStatementFormat, 60 | ): AuthenticatorType { 61 | return when (authenticationMethod) { 62 | AuthenticationMethod.Biometric -> { 63 | when (attestationStatementFormat) { 64 | AttestationStatementFormat.NONE -> BiometricNone 65 | AttestationStatementFormat.ANDROID_KEY -> BiometricAndroidKey 66 | } 67 | } 68 | AuthenticationMethod.DeviceCredential -> { 69 | when (attestationStatementFormat) { 70 | AttestationStatementFormat.NONE -> DeviceCredentialNone 71 | AttestationStatementFormat.ANDROID_KEY -> DeviceCredentialAndroidKey 72 | } 73 | } 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/CborSerializable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import co.nstant.`in`.cbor.CborBuilder 20 | import co.nstant.`in`.cbor.CborEncoder 21 | import co.nstant.`in`.cbor.builder.AbstractBuilder 22 | import co.nstant.`in`.cbor.builder.MapBuilder 23 | import java.io.ByteArrayOutputStream 24 | import jp.co.lycorp.webauthn.exceptions.WebAuthnException 25 | 26 | interface CborSerializable { 27 | fun ?> toCBOR(builder: MapBuilder): T 28 | 29 | fun toCBOR(canonical: Boolean = true): ByteArray { 30 | try { 31 | val baos = ByteArrayOutputStream() 32 | CborEncoder(baos).encode(toCBOR(CborBuilder().startMap()).build()) 33 | return baos.toByteArray() 34 | } catch (e: Exception) { 35 | throw WebAuthnException.EncodingException("Cannot convert Attestation Object to CBOR.", e) 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/CollectedClientData.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | data class CollectedClientData( 20 | val type: String, 21 | val challenge: String, 22 | val origin: String, 23 | ) 24 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/CredentialProtection.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | class CredentialProtection { 20 | val credentialProtectionPolicy: String = "USER_VERIFICATION_REQUIRED" 21 | val enforceCredentialProtectionPolicy: Boolean = true 22 | } 23 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/Fido2PromptInfo.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | data class Fido2PromptInfo( 20 | val title: CharSequence? = "Biometric Authentication", 21 | val subtitle: CharSequence? = "Enter biometric credentials to proceed", 22 | val description: CharSequence? = "Input your Fingerprint or FaceID to ensure it's you!", 23 | val negativeButtonText: CharSequence? = "Cancel", 24 | ) 25 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/Fido2UserAuthResult.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import java.security.Signature 20 | 21 | data class Fido2UserAuthResult( 22 | var signature: Signature? 23 | ) 24 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialCreationOptions.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | class PublicKeyCredentialCreationOptions( 20 | val rp: PublicKeyCredentialRpEntity, 21 | val user: PublicKeyCredentialUserEntity, 22 | val challenge: String, 23 | val publicKeyCredentialParams: List, 24 | val excludeCredentials: List?, 25 | val authenticatorSelection: AuthenticatorSelectionCriteria?, 26 | val attestation: AttestationConveyancePreference = AttestationConveyancePreference.DIRECT, 27 | val extensions: ClientExtensionInput?, 28 | ) 29 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialDescriptor.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | class PublicKeyCredentialDescriptor( 20 | var type: String, 21 | var id: String, 22 | var transports: List? = listOf(AuthenticatorTransport.INTERNAL), 23 | ) 24 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialParams.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | data class PublicKeyCredentialParams( 20 | val type: PublicKeyCredentialType, 21 | val alg: COSEAlgorithmIdentifier, 22 | ) 23 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialRequestOptions.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | class PublicKeyCredentialRequestOptions( 20 | val challenge: String, 21 | val rpId: String, 22 | val allowCredentials: List?, 23 | val userVerification: UserVerificationRequirement = UserVerificationRequirement.PREFERRED, 24 | val extensions: ClientExtensionInput?, 25 | ) 26 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialResult.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import jp.co.lycorp.webauthn.util.base64urlToByteArray 20 | 21 | /** 22 | * The result of the WebAuthn registration process. 23 | * 24 | * @property id Base64url encoding of the credential ID. 25 | * @property authenticatorAttestationResponse The authenticator's attestation response. 26 | * @property clientExtensionsOutput Optional client extension outputs. 27 | * @property rawId ByteArray representation of the credential ID. 28 | * @property type The type of public key credential. 29 | */ 30 | class PublicKeyCredentialCreateResult( 31 | val id: String, 32 | val authenticatorAttestationResponse: jp.co.lycorp.webauthn.model.AuthenticatorAttestationResponse, 33 | val clientExtensionsOutput: ClientExtensionsOutput? = null, 34 | ) { 35 | var rawId: ByteArray = id.base64urlToByteArray() 36 | val type: String = PublicKeyCredentialType.PUBLIC_KEY.value 37 | } 38 | 39 | /** 40 | * The result of the WebAuthn authentication process. 41 | * 42 | * @property id Base64url encoding of the credential ID. 43 | * @property authenticatorAssertionResponse The authenticator's assertion response. 44 | * @property clientExtensionsOutput Optional client extension outputs. 45 | * @property rawId ByteArray representation of the credential ID. 46 | * @property type The type of public key credential. 47 | */ 48 | class PublicKeyCredentialGetResult( 49 | val id: String, 50 | val authenticatorAssertionResponse: jp.co.lycorp.webauthn.model.AuthenticatorAssertionResponse, 51 | val clientExtensionsOutput: ClientExtensionsOutput? = null, 52 | ) { 53 | var rawId: ByteArray = id.base64urlToByteArray() 54 | val type: String = PublicKeyCredentialType.PUBLIC_KEY.value 55 | } 56 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialRpEntity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | class PublicKeyCredentialRpEntity( 20 | val id: String, 21 | val name: String, 22 | ) 23 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialSource.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | import java.util.UUID 20 | 21 | data class PublicKeyCredentialSource( 22 | val type: String = jp.co.lycorp.webauthn.model.PublicKeyCredentialType.PUBLIC_KEY.value, 23 | var id: String, 24 | val rpId: String, 25 | val userHandle: String?, // base64url encoding of the user handle 26 | val aaguid: UUID, 27 | ) { 28 | override fun equals(other: Any?): Boolean { 29 | if (this === other) return true 30 | if (javaClass != other?.javaClass) return false 31 | 32 | other as jp.co.lycorp.webauthn.model.PublicKeyCredentialSource 33 | 34 | if (type != other.type) return false 35 | if (!id.contentEquals(other.id)) return false 36 | if (rpId != other.rpId) return false 37 | if (userHandle != null) { 38 | if (other.userHandle == null) return false 39 | if (!userHandle.contentEquals(other.userHandle)) return false 40 | } else if (other.userHandle != null) { 41 | return false 42 | } 43 | return aaguid == other.aaguid 44 | } 45 | 46 | override fun hashCode(): Int { 47 | var result = type.hashCode() 48 | result = 31 * result + id.hashCode() 49 | result = 31 * result + rpId.hashCode() 50 | result = 31 * result + (userHandle?.hashCode() ?: 0) 51 | result = 31 * result + aaguid.hashCode() 52 | return result 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialType.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | enum class PublicKeyCredentialType(val value: String) { 20 | PUBLIC_KEY("public-key"), 21 | ; 22 | 23 | companion object { 24 | fun fromValue(value: String): PublicKeyCredentialType? { 25 | return values().find { it.value == value } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/model/PublicKeyCredentialUserEntity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.model 18 | 19 | data class PublicKeyCredentialUserEntity( 20 | val id: String, // same as user handle 21 | val name: String, 22 | val displayName: String, 23 | ) 24 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/rp/RelyingParty.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.rp 18 | 19 | import jp.co.lycorp.webauthn.model.AttestationConveyancePreference 20 | import jp.co.lycorp.webauthn.model.AuthenticatorSelectionCriteria 21 | import jp.co.lycorp.webauthn.model.ClientExtensionInput 22 | import jp.co.lycorp.webauthn.model.CredentialProtection 23 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialCreateResult 24 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialDescriptor 25 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialGetResult 26 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialParams 27 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialRpEntity 28 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialUserEntity 29 | import jp.co.lycorp.webauthn.model.UserVerificationRequirement 30 | 31 | /** 32 | * Interface for Relying Party operations in WebAuthn. 33 | * Defines methods for registration and authentication processes. 34 | */ 35 | interface RelyingParty { 36 | 37 | /** 38 | * Generates and returns the data required to initiate a WebAuthn registration process. 39 | * 40 | * @param options The registration options containing parameters like attestation, authenticator selection, etc. 41 | * @return RegistrationData The data required to initiate the registration process. 42 | */ 43 | suspend fun getRegistrationData(options: RegistrationOptions): RegistrationData 44 | 45 | /** 46 | * Verifies the result of a WebAuthn registration process. 47 | * 48 | * @param result The result of the registration process. 49 | */ 50 | suspend fun verifyRegistration(result: PublicKeyCredentialCreateResult) 51 | 52 | /** 53 | * Generates and returns the data required to initiate a WebAuthn authentication process. 54 | * 55 | * @param options The authentication options containing parameters like user verification, username, etc. 56 | * @return AuthenticationData The data required to initiate the authentication process. 57 | */ 58 | suspend fun getAuthenticationData(options: AuthenticationOptions): AuthenticationData 59 | 60 | /** 61 | * Verifies the result of a WebAuthn authentication process. 62 | * 63 | * @param result The result of the authentication process. 64 | */ 65 | suspend fun verifyAuthentication(result: PublicKeyCredentialGetResult) 66 | } 67 | 68 | data class RegistrationOptions( 69 | val attestation: AttestationConveyancePreference, 70 | val authenticatorSelection: AuthenticatorSelectionCriteria?, 71 | val credProtect: CredentialProtection?, 72 | val displayName: String, 73 | val username: String 74 | ) 75 | 76 | data class AuthenticationOptions( 77 | val userVerification: UserVerificationRequirement, 78 | val username: String 79 | ) 80 | 81 | data class RegistrationData( 82 | val attestation: AttestationConveyancePreference, 83 | val authenticatorSelection: AuthenticatorSelectionCriteria?, 84 | val challenge: String, 85 | val excludeCredentials: List?, 86 | val extensions: ClientExtensionInput?, 87 | val pubKeyCredParams: List, 88 | val rp: PublicKeyCredentialRpEntity, 89 | val user: PublicKeyCredentialUserEntity 90 | ) 91 | 92 | data class AuthenticationData( 93 | val allowCredentials: List?, 94 | val challenge: String, 95 | val extensions: ClientExtensionInput?, 96 | val rpId: String, 97 | val userVerification: UserVerificationRequirement 98 | ) 99 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/util/Constants.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.util 18 | 19 | const val CRED_ID_SIZE = 32 20 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/util/Encoding.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.util 18 | 19 | import java.util.Base64 20 | import jp.co.lycorp.webauthn.exceptions.WebAuthnException 21 | 22 | fun String.toBase64url(): String { 23 | try { 24 | return Base64.getUrlEncoder().withoutPadding().encodeToString(this.encodeToByteArray()) 25 | } catch (e: Exception) { 26 | throw WebAuthnException.UtilityException("Failed to encode String to base64url String", e) 27 | } 28 | } 29 | 30 | fun String.base64urlToString(): String { 31 | try { 32 | return Base64.getUrlDecoder().decode(this).decodeToString() 33 | } catch (e: Exception) { 34 | throw WebAuthnException.UtilityException("Failed to decode base64url String to String", e) 35 | } 36 | } 37 | 38 | fun String.base64urlToByteArray(): ByteArray { 39 | try { 40 | return Base64.getUrlDecoder().decode(this) 41 | } catch (e: Exception) { 42 | throw WebAuthnException.UtilityException("Failed to decode base64url String to ByteArray", e) 43 | } 44 | } 45 | 46 | fun ByteArray.toBase64url(): String { 47 | try { 48 | return Base64.getUrlEncoder().withoutPadding().encodeToString(this) 49 | } catch (e: Exception) { 50 | throw WebAuthnException.UtilityException("Failed to encode ByteArray to base64url String", e) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/util/Fido2Util.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.util 18 | 19 | import android.content.Context 20 | import android.content.pm.PackageManager 21 | import android.os.Build 22 | import android.util.Base64 23 | import java.io.ByteArrayInputStream 24 | import java.io.InputStream 25 | import java.security.MessageDigest 26 | import java.security.SecureRandom 27 | import java.security.cert.CertificateFactory 28 | import java.security.cert.X509Certificate 29 | import jp.co.lycorp.webauthn.exceptions.WebAuthnException 30 | 31 | class Fido2Util { 32 | companion object { 33 | fun getPackageFacetID(context: Context): String { 34 | val cert: ByteArray = if (Build.VERSION.SDK_INT >= 33) { 35 | context.packageManager.getPackageInfo( 36 | context.packageName, 37 | PackageManager.PackageInfoFlags.of(PackageManager.GET_SIGNING_CERTIFICATES.toLong()) 38 | ).signingInfo!!.apkContentsSigners[0].toByteArray() 39 | } else { 40 | context.packageManager.getPackageInfo( 41 | context.packageName, 42 | PackageManager.GET_SIGNING_CERTIFICATES 43 | ).signingInfo!!.apkContentsSigners[0].toByteArray() 44 | } 45 | val input: InputStream = ByteArrayInputStream(cert) 46 | val cf = CertificateFactory.getInstance("X509") 47 | val certificate: X509Certificate = cf.generateCertificate(input) as X509Certificate 48 | val md = MessageDigest.getInstance("SHA256") 49 | val hash = md.digest(certificate.encoded) 50 | 51 | // According to the "FIDO AppID and Facet Specification" v2.0 specification draft 52 | // Supposed to be default (non URL safe) encoding 53 | return "android:apk-key-hash-sha256:" + 54 | Base64.encodeToString(hash, Base64.DEFAULT or Base64.NO_WRAP or Base64.NO_PADDING) 55 | } 56 | 57 | fun generateRandomByteArray(numByte: Int): ByteArray { 58 | try { 59 | return ByteArray(numByte).also { SecureRandom().nextBytes(it) } 60 | } catch (e: Throwable) { 61 | throw WebAuthnException.UtilityException("Cannot generate random byte array.", e) 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /webauthn/src/main/java/jp/co/lycorp/webauthn/util/SecureExecutionHelper.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.util 18 | 19 | import java.security.Key 20 | import java.security.KeyStore 21 | import java.security.KeyStoreException 22 | import java.security.PublicKey 23 | import java.security.cert.X509Certificate 24 | import jp.co.lycorp.webauthn.exceptions.WebAuthnException 25 | 26 | /** 27 | * Helper class for secure execution 28 | */ 29 | internal object SecureExecutionHelper { 30 | private val lock = Any() 31 | 32 | fun deleteKey(keyAlias: String) { 33 | synchronized(lock) { 34 | try { 35 | KeyStore.getInstance("AndroidKeyStore").also { 36 | it.load(null) 37 | it.deleteEntry(keyAlias) 38 | } 39 | } catch (e: Throwable) { 40 | throw WebAuthnException.SecureExecutionException("Cannot delete key from KeyStore.", e) 41 | } 42 | } 43 | } 44 | 45 | fun getKey(keyAlias: String): Key? { 46 | synchronized(lock) { 47 | try { 48 | val keyStore = 49 | KeyStore.getInstance("AndroidKeyStore").also { 50 | it.load(null, null) 51 | } 52 | return keyStore.getKey(keyAlias, null) 53 | } catch (e: Throwable) { 54 | throw WebAuthnException.SecureExecutionException("Cannot fetch key from KeyStore.", e) 55 | } 56 | } 57 | } 58 | 59 | fun getX509Certificates(keyAlias: String): List { 60 | synchronized(lock) { 61 | try { 62 | val keyStore = 63 | KeyStore.getInstance("AndroidKeyStore").also { 64 | it.load(null, null) 65 | } 66 | val certChain = keyStore.getCertificateChain(keyAlias) 67 | ?: throw KeyStoreException("Cannot find certificate chain") 68 | val certChainList = certChain.toList() 69 | return certChainList.map { it as X509Certificate } 70 | } catch (e: Throwable) { 71 | throw WebAuthnException.SecureExecutionException("Cannot fetch X509 certificate from KeyStore.", e) 72 | } 73 | } 74 | } 75 | 76 | fun getX509Certificate(keyAlias: String): X509Certificate { 77 | synchronized(lock) { 78 | try { 79 | val keyStore = 80 | KeyStore.getInstance("AndroidKeyStore").also { 81 | it.load(null, null) 82 | } 83 | val certificate = keyStore.getCertificate(keyAlias) 84 | ?: throw KeyStoreException("Cannot find certificate") 85 | return certificate as X509Certificate 86 | } catch (e: Throwable) { 87 | throw WebAuthnException.SecureExecutionException("Cannot fetch X509 certificate from KeyStore.", e) 88 | } 89 | } 90 | } 91 | 92 | fun containAlias(keyAlias: String): Boolean { 93 | synchronized(lock) { 94 | try { 95 | val keyStore = 96 | KeyStore.getInstance("AndroidKeyStore").also { 97 | it.load(null, null) 98 | } 99 | return keyStore.containsAlias(keyAlias) 100 | } catch (e: Throwable) { 101 | throw WebAuthnException.SecureExecutionException("Cannot check key alias from KeyStore.", e) 102 | } 103 | } 104 | } 105 | 106 | fun getPublicKey(keyAlias: String): PublicKey { 107 | try { 108 | val x509CertificateChain = getX509Certificates(keyAlias) 109 | return x509CertificateChain[0].publicKey 110 | } catch (e: Throwable) { 111 | throw WebAuthnException.SecureExecutionException("Cannot fetch public key from KeyStore.", e) 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /webauthn/src/test/java/jp/co/lycorp/webauthn/PublicKeyCredentialTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn 18 | 19 | import android.content.Context 20 | import android.util.Log 21 | import androidx.fragment.app.FragmentActivity 22 | import com.google.common.truth.Truth.assertThat 23 | import io.mockk.coEvery 24 | import io.mockk.every 25 | import io.mockk.mockk 26 | import io.mockk.mockkObject 27 | import io.mockk.mockkStatic 28 | import java.security.KeyPairGenerator 29 | import jp.co.lycorp.webauthn.authenticator.Authenticator 30 | import jp.co.lycorp.webauthn.authenticator.AuthenticatorProvider 31 | import jp.co.lycorp.webauthn.exceptions.WebAuthnException 32 | import jp.co.lycorp.webauthn.model.AttestationConveyancePreference 33 | import jp.co.lycorp.webauthn.model.AttestationStatementFormat 34 | import jp.co.lycorp.webauthn.model.AuthenticationMethod 35 | import jp.co.lycorp.webauthn.model.AuthenticatorGetAssertionResult 36 | import jp.co.lycorp.webauthn.model.AuthenticatorMakeCredentialResult 37 | import jp.co.lycorp.webauthn.model.AuthenticatorSelectionCriteria 38 | import jp.co.lycorp.webauthn.model.AuthenticatorType 39 | import jp.co.lycorp.webauthn.model.COSEAlgorithmIdentifier 40 | import jp.co.lycorp.webauthn.model.ClientExtensionInput 41 | import jp.co.lycorp.webauthn.model.CredentialProtection 42 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialDescriptor 43 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialParams 44 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialRpEntity 45 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialSource 46 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialType 47 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialUserEntity 48 | import jp.co.lycorp.webauthn.model.UserVerificationRequirement 49 | import jp.co.lycorp.webauthn.publickeycredential.PublicKeyCredential 50 | import jp.co.lycorp.webauthn.rp.AuthenticationData 51 | import jp.co.lycorp.webauthn.rp.AuthenticationOptions 52 | import jp.co.lycorp.webauthn.rp.RegistrationData 53 | import jp.co.lycorp.webauthn.rp.RegistrationOptions 54 | import jp.co.lycorp.webauthn.rp.RelyingParty 55 | import jp.co.lycorp.webauthn.util.Fido2Util 56 | import jp.co.lycorp.webauthn.util.MockCredentialSourceStorage 57 | import jp.co.lycorp.webauthn.util.toBase64url 58 | import kotlin.reflect.KClass 59 | import kotlinx.coroutines.async 60 | import kotlinx.coroutines.runBlocking 61 | import kotlinx.coroutines.test.runTest 62 | import org.junit.jupiter.api.BeforeEach 63 | import org.junit.jupiter.api.Test 64 | 65 | class PublicKeyCredentialTest { 66 | 67 | private val mockActivity = mockk() 68 | private val mockContext = mockk() 69 | private val mockAuthenticatorProvider = mockk() 70 | private val mockRelyingParty = mockk() 71 | private val mockAuthenticator = mockk() 72 | private val mockDb = MockCredentialSourceStorage() 73 | 74 | private lateinit var publicKeyCredential: PublicKeyCredential 75 | 76 | private val dummyByteArray = ByteArray(32) { 0 } 77 | private val dummyRpEntity = PublicKeyCredentialRpEntity("example.com", "Example Relying Party") 78 | private val dummyUserEntity = PublicKeyCredentialUserEntity("user123", "User Name", "Display Name") 79 | private val es256CredParams = PublicKeyCredentialParams( 80 | PublicKeyCredentialType.PUBLIC_KEY, 81 | COSEAlgorithmIdentifier.ES256 82 | ) 83 | private val registeredCredId = Fido2Util.generateRandomByteArray(32).toBase64url() 84 | private val registeredRpEntity = PublicKeyCredentialRpEntity("registered.com", "Example Registered Relying Party") 85 | private val registeredUserEntity = PublicKeyCredentialUserEntity("reg_user", "Reg User", "Reg User") 86 | private val registeredCredSource = jp.co.lycorp.webauthn.model.PublicKeyCredentialSource( 87 | id = registeredCredId, 88 | rpId = registeredRpEntity.id, 89 | userHandle = registeredUserEntity.id, 90 | aaguid = AuthenticatorType.BiometricAndroidKey.aaguid, 91 | ) 92 | private val registeredCredDescriptor = PublicKeyCredentialDescriptor( 93 | type = PublicKeyCredentialType.PUBLIC_KEY.value, 94 | id = registeredCredSource.id, 95 | transports = null, 96 | ) 97 | 98 | private val dummyRegistrationData: RegistrationData = RegistrationData( 99 | attestation = AttestationConveyancePreference.DIRECT, 100 | authenticatorSelection = AuthenticatorSelectionCriteria(null, UserVerificationRequirement.REQUIRED.value), 101 | challenge = Fido2Util.generateRandomByteArray(32).toBase64url(), 102 | excludeCredentials = emptyList(), 103 | extensions = ClientExtensionInput(), 104 | pubKeyCredParams = listOf(es256CredParams), 105 | rp = dummyRpEntity, 106 | user = dummyUserEntity, 107 | ) 108 | private val dummyAuthenticationData: AuthenticationData = AuthenticationData( 109 | allowCredentials = listOf(registeredCredDescriptor), 110 | challenge = Fido2Util.generateRandomByteArray(32).toBase64url(), 111 | extensions = ClientExtensionInput(), 112 | rpId = dummyRpEntity.id, 113 | userVerification = UserVerificationRequirement.REQUIRED, 114 | ) 115 | private val dummyRegistrationOptions: RegistrationOptions = RegistrationOptions( 116 | AttestationConveyancePreference.DIRECT, 117 | AuthenticatorSelectionCriteria(null, UserVerificationRequirement.PREFERRED.value), 118 | CredentialProtection(), 119 | dummyUserEntity.displayName, 120 | dummyUserEntity.name 121 | ) 122 | private val dummyAuthenticationOptions: AuthenticationOptions = AuthenticationOptions( 123 | UserVerificationRequirement.PREFERRED, 124 | dummyUserEntity.name 125 | ) 126 | 127 | private val keyPair = KeyPairGenerator.getInstance("EC").apply { initialize(256) }.generateKeyPair() 128 | 129 | @BeforeEach 130 | fun setUp() { 131 | publicKeyCredential = PublicKeyCredential( 132 | rpClient = mockRelyingParty, 133 | db = mockDb, 134 | authenticationMethod = AuthenticationMethod.Biometric, 135 | attestationStatement = AttestationStatementFormat.ANDROID_KEY, 136 | authenticatorProvider = mockAuthenticatorProvider, 137 | ) 138 | 139 | // Mock static Log class 140 | mockkStatic(Log::class) 141 | every { Log.v(any(), any()) } returns 0 142 | every { Log.d(any(), any()) } returns 0 143 | every { Log.i(any(), any()) } returns 0 144 | every { Log.e(any(), any()) } returns 0 145 | 146 | // Mock Activity and Context 147 | coEvery { mockActivity.applicationContext } returns mockContext 148 | 149 | // Mock Biometric Authenticator actions 150 | coEvery { 151 | mockAuthenticator.makeCredential(any(), any(), any(), any(), any(), any(), any()) 152 | } returns Result.success(AuthenticatorMakeCredentialResult(dummyByteArray, dummyByteArray)) 153 | coEvery { 154 | mockAuthenticator.getAssertion(any(), any(), any(), any(), any()) 155 | } returns Result.success( 156 | AuthenticatorGetAssertionResult(dummyByteArray, dummyByteArray, dummyByteArray, dummyByteArray) 157 | ) 158 | 159 | // Mock AuthenticatorProvider 160 | coEvery { mockAuthenticatorProvider.getAuthenticator(any(), any()) } returns mockAuthenticator 161 | 162 | // Mock RelyingParty actions 163 | coEvery { mockRelyingParty.getRegistrationData(any()) } returns dummyRegistrationData 164 | coEvery { mockRelyingParty.verifyRegistration(any()) } returns Unit 165 | coEvery { mockRelyingParty.getAuthenticationData(any()) } returns dummyAuthenticationData 166 | coEvery { mockRelyingParty.verifyAuthentication(any()) } returns Unit 167 | 168 | // Mock Fido2Util object 169 | mockkObject(Fido2Util) 170 | coEvery { Fido2Util.getPackageFacetID(any()) } returns "TEST_FACET_ID" 171 | } 172 | 173 | @Test 174 | fun `should throw TypeException when options user id length is invalid`() = runBlocking { 175 | listOf( 176 | generateString("a", 0), 177 | generateString("a", 65), 178 | ).forEach { invalidUserId -> 179 | coEvery { 180 | mockRelyingParty.getRegistrationData(any()) 181 | } returns dummyRegistrationData.copy(user = dummyUserEntity.copy(id = invalidUserId)) 182 | 183 | val result = publicKeyCredential.create(mockActivity, dummyRegistrationOptions, null) 184 | assertThat(result.isFailure).isTrue() 185 | assertThat(result.exceptionOrNull()).isInstanceOf(WebAuthnException.CoreException.TypeException::class.java) 186 | } 187 | } 188 | 189 | @Test 190 | fun `should work well when register and authenticate with valid parameters`() = runBlocking { 191 | coEvery { mockAuthenticatorProvider.getAuthenticator(any(), any()) } returns mockAuthenticator 192 | 193 | val regResult = publicKeyCredential.create(mockActivity, dummyRegistrationOptions, null) 194 | assertThat(regResult.isSuccess).isTrue() 195 | 196 | val authResult = publicKeyCredential.get(mockActivity, dummyAuthenticationOptions, null) 197 | assertThat(authResult.isSuccess).isTrue() 198 | } 199 | 200 | @Test 201 | fun `should allow concurrent execution of register with different rpEntity`(): Unit = runBlocking { 202 | val times = 10 203 | val registeredRpId = mutableListOf() 204 | coEvery { 205 | mockAuthenticator.makeCredential(any(), any(), any(), any(), any(), any(), any()) 206 | } coAnswers { 207 | val rpEntity: PublicKeyCredentialRpEntity = secondArg() 208 | if (rpEntity.id !in registeredRpId) { 209 | registeredRpId.add(rpEntity.id) 210 | Result.success(AuthenticatorMakeCredentialResult(dummyByteArray, dummyByteArray)) 211 | } else { 212 | Result.failure(WebAuthnException.CoreException.InvalidStateException()) 213 | } 214 | } 215 | 216 | performConcurrentExecution(times) { 217 | val newRpEntity = PublicKeyCredentialRpEntity("https://test-rp.com/$it", "test_rp") 218 | coEvery { mockRelyingParty.getRegistrationData(any()) } returns RegistrationData( 219 | attestation = AttestationConveyancePreference.DIRECT, 220 | authenticatorSelection = AuthenticatorSelectionCriteria( 221 | null, UserVerificationRequirement.REQUIRED.value 222 | ), 223 | challenge = Fido2Util.generateRandomByteArray(32).toBase64url(), 224 | excludeCredentials = emptyList(), 225 | extensions = ClientExtensionInput(), 226 | pubKeyCredParams = listOf(es256CredParams), 227 | rp = newRpEntity, 228 | user = dummyUserEntity, 229 | ) 230 | publicKeyCredential.create(mockActivity, dummyRegistrationOptions, null) 231 | } 232 | } 233 | 234 | @Test 235 | fun `should propagate exception when Authenticator throws exception`() = runBlocking { 236 | listOf( 237 | WebAuthnException.CoreException.InvalidStateException::class, 238 | WebAuthnException.CoreException.NotAllowedException::class, 239 | ).forEach { exceptionType -> 240 | coEvery { 241 | mockAuthenticator.makeCredential(any(), any(), any(), any(), any(), any(), any()) 242 | } returns Result.failure(getExceptionBasedOnType(exceptionType)) 243 | 244 | val regResult = publicKeyCredential.create(mockActivity, dummyRegistrationOptions, null) 245 | assertThat(regResult.isFailure).isTrue() 246 | assertThat(regResult.exceptionOrNull()).isInstanceOf(exceptionType.java) 247 | 248 | coEvery { 249 | mockAuthenticator.getAssertion(any(), any(), any(), any(), any()) 250 | } returns Result.failure(getExceptionBasedOnType(exceptionType)) 251 | 252 | val authResult = publicKeyCredential.get(mockActivity, dummyAuthenticationOptions, null) 253 | assertThat(authResult.isFailure).isTrue() 254 | assertThat(authResult.exceptionOrNull()).isInstanceOf(exceptionType.java) 255 | } 256 | } 257 | 258 | private fun generateString(pattern: String, length: Int): String { 259 | return pattern.repeat((length + pattern.length - 1) / pattern.length).take(length) 260 | } 261 | 262 | private fun performConcurrentExecution(times: Int, block: suspend (Int) -> Unit) = runTest { 263 | (1..times).map { 264 | async { 265 | block(it) 266 | } 267 | }.map { it.await() } 268 | } 269 | 270 | private fun getExceptionBasedOnType(exceptionClass: KClass): Throwable { 271 | return when (exceptionClass) { 272 | WebAuthnException.CoreException.NotAllowedException::class -> 273 | WebAuthnException.CoreException.NotAllowedException() 274 | WebAuthnException.CoreException.InvalidStateException::class -> 275 | WebAuthnException.CoreException.InvalidStateException() 276 | else -> Exception("Unknown exception type") 277 | } 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /webauthn/src/test/java/jp/co/lycorp/webauthn/util/MockCredentialSourceStorage.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 LY Corporation 3 | * 4 | * LY Corporation licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package jp.co.lycorp.webauthn.util 18 | 19 | import java.util.UUID 20 | import jp.co.lycorp.webauthn.db.CredentialSourceStorage 21 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialSource 22 | import jp.co.lycorp.webauthn.model.PublicKeyCredentialType 23 | 24 | class MockCredentialSourceStorage : CredentialSourceStorage { 25 | private var credSourceTable: MutableList = mutableListOf() 26 | 27 | override fun store(credSource: jp.co.lycorp.webauthn.model.PublicKeyCredentialSource) { 28 | val credSourceEntity = TestPubKeyCredSourceEntity( 29 | credType = PublicKeyCredentialType.PUBLIC_KEY.value, 30 | aaguid = credSource.aaguid, 31 | credId = credSource.id, 32 | rpId = credSource.rpId, 33 | userHandle = credSource.userHandle, 34 | signatureCounter = 0L, 35 | ) 36 | credSourceTable.add(credSourceEntity) 37 | } 38 | override fun load(credId: String): jp.co.lycorp.webauthn.model.PublicKeyCredentialSource? { 39 | val credSourceEntity = credSourceTable.firstOrNull { it.credId.contentEquals(credId) } 40 | return credSourceEntity?.let { 41 | jp.co.lycorp.webauthn.model.PublicKeyCredentialSource( 42 | type = it.credType, 43 | id = it.credId, 44 | rpId = it.rpId, 45 | userHandle = it.userHandle, 46 | aaguid = it.aaguid, 47 | ) 48 | } 49 | } 50 | 51 | override fun loadAll(aaguid: UUID?): List { 52 | return credSourceTable 53 | .filter { entity -> 54 | aaguid == null || entity.aaguid == aaguid 55 | } 56 | .map { entity -> 57 | jp.co.lycorp.webauthn.model.PublicKeyCredentialSource( 58 | type = entity.credType, 59 | id = entity.credId, 60 | rpId = entity.rpId, 61 | userHandle = entity.userHandle, 62 | aaguid = entity.aaguid, 63 | ) 64 | } 65 | } 66 | 67 | override fun delete(credId: String) { 68 | credSourceTable = credSourceTable.filter { it.credId != credId }.toMutableList() 69 | } 70 | 71 | override fun increaseSignatureCounter(credId: String) { 72 | val credSourceEntity = credSourceTable.firstOrNull { it.credId.contentEquals(credId) } 73 | credSourceEntity?.let { 74 | it.signatureCounter += 1 75 | } 76 | } 77 | override fun getSignatureCounter(credId: String): UInt = 0u 78 | 79 | fun removeAllData() { 80 | credSourceTable = mutableListOf() 81 | } 82 | } 83 | 84 | data class TestPubKeyCredSourceEntity( 85 | val credType: String, 86 | var credId: String, 87 | val rpId: String, 88 | val userHandle: String?, 89 | val aaguid: UUID, 90 | var signatureCounter: Long, 91 | ) 92 | --------------------------------------------------------------------------------