Skip to content
Snippets Groups Projects
Commit 4284d0a0 authored by Christian Kollmann's avatar Christian Kollmann
Browse files

Import vclib

parents
Branches
Tags
No related merge requests found
Showing
with 1442 additions and 0 deletions
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
local.properties
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
# Changelog
Release 1.7.1:
- Remove references to `PupilIdCredential`, will be moved to separate library
Release 1.6.0:
- Store attachments with reference to VC (changes `SubjectCredentialStore`)
Release 1.5.0:
- Update dependencies: Kotlin 1.8.0, `KmmResult` 1.4.0
- Remove "plain" instances of classes, not used on iOS
Release 1.4.0:
- Remove `photo` from `PupilIdCredential`
- Remove `pupilId` from `PupilIdCredential`
- Add `cardId` to `PupilIdCredential`
- Add `pictureHash` to `PupilIdCredential`
- Add `scaledPictureHash` to `PupilIdCredential`
- Transport attachments in `IssueCredential` protocol, which will contain photos (as binary blobs)
- Update dependencies: Kotlin 1.7.21, Serialization 1.4.1, Kotest 5.5.4
Release 1.3.12:
- Update to `KmmResult` 1.1
Release 1.3.11:
- Migrate public API to use `KmmResult`: Return a `failure` with a custom Exception if something goes wrong, otherwise return a `success` with a custom data class.
Release 1.3.10:
- Implement validating JWS with jsonWebKey and certificates from header
- Export `BitSet` to Kotlin/Native, i.e. do not `inline` the class
Release 1.3.9:
- True multiplatform BitSet implementation
LICENSE 0 → 100644
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
README.md 0 → 100644
# KMM VC Library
This [Kotlin Mulitplatform](https://kotlinlang.org/docs/multiplatform.html) library implements the [W3C VC Data Model](https://w3c.github.io/vc-data-model/) to support several use cases of verifiable credentials, verifiable presentations, and validation thereof. This library may be shared between Wallet Apps, Verifier Apps and a Backend Service issuing credentials.
## Architecture
This library was built with [Kotlin Mulitplatform](https://kotlinlang.org/docs/multiplatform.html) and [Mulitplatform Mobile](https://kotlinlang.org/lp/mobile/) in mind. Its primary targets are JVM, Android and iOS. In order to achieve smooth usage especially under iOS, there have been some notable design decisions:
- Code interfacing with client implementations uses the return type `KmmResult` to transport the `Success` case (i.e. a custom data type) as well as potential errors from native implementations as a `Failure`.
- Native implementations can be plugged in by implementing interfaces, e.g. `CryptoService`, as opposed to callback functions.
- Use of primitve data types for constructor properties instead of e.g. kotlinx datetime types.
- This library provides some "default" implementations, e.g. `DefaultCryptoService` to test as much code as possible from the `commonMain` module.
- Some classes feature additional constructors or factory methods with a shorter argument list because the default arguments are lost when called from Swift.
Notable features for mulitplatform are:
- Use of [Napier](https://github.com/AAkira/Napier) as the logging framework
- Use of [Kotest](https://kotest.io/) for unit tests
- Implementation of a BitSet in pure Kotlin, see `KmmBitSet`
- Implementation of a ZLIB service in Kotlin with native parts, see `ZlibService`
- Implementation of JWS and JWE operations in pure Kotlin (delegating to native crypto), see `JwsService`
- Abstraction of several cryptographic primitives, to be implemented in native code, see `CryptoService`
The main entry point for applications is an instance of `HolderAgent`, `VerifierAgent` or `IssuerAgent`, according to the nomenclature from the [W3C VC Data Model](https://w3c.github.io/vc-data-model/).
One central aspect is communication between agents. We implement protocols for issuing credentials and presenting proofs from ARIES, i.e. [ARIES RFC 0453 Issue Credential V2](https://github.com/hyperledger/aries-rfcs/tree/main/features/0453-issue-credential-v2) and [ARIES RFC 0454 Present Proof V2](https://github.com/hyperledger/aries-rfcs/tree/main/features/0454-present-proof-v2). A single run of a protocol is implemented by the `*Protocol` classes, whereas the `*Messenger` classes should be used by applications to manage several runs of a protocol.
There is also a simple implementation of [Self-Issued OpenID Provider v2](https://openid.net/specs/openid-connect-self-issued-v2-1_0.html), see `OidcSiopProtocol`.
Many classes define several constructor parameters, some of them with default values, to enable a simple form of dependency injection. Implementers are advised to specify the parameter names of arguments passed to increase readability and prepare for future extensions.
See also [DEVELOPMENT.md](DEVELOPMENT.md)
## Limitations
- For Verifiable Credentials and Presentations, only the JWT proof mechanism is implemented.
- Json Web Keys always use a `kid` of `did:key:mEpA...` with a custom, uncompressed representation of `secp256r1` keys.
- Several parts of the W3C VC Data Model have not been fully implemented, i.e. everything around resolving cryptographic material.
- Cryptographic operations are implemented for EC cryptography on the `secp256r1` curve to fully support hardware-backed keys on Android and iOS. However, the enum classes for cryptographic primitives may be extended to support other algorithms.
## iOS Implementation
The `DefaultCryptoService` for iOS should not be used in production as it does not implement encryption, decryption, key agreement and message digests correctly.
A more correct implementation in Swift, using [Apple CryptoKit](https://developer.apple.com/documentation/cryptokit/) would be:
```Swift
import Foundation
import CryptoKit
// KeyChainService.loadPrivateKey() provides a SecureEnclave.P256.Signing.PrivateKey?
public class VcLibCryptoServiceCryptoKit: CryptoService {
public var jwsAlgorithm: JwsAlgorithm
public var keyId: String
public var certificateChain: [Data]
private let jsonWebKey: JsonWebKey
private let keyChainService: KeyChainService
public init?(keyChainService: KeyChainService) {
guard let privateKey = keyChainService.loadPrivateKey() else {
return nil
}
self.keyChainService = keyChainService
self.jsonWebKey = JsonWebKey.companion.fromAnsiX963Bytes(type: .ec, curve: .secp256R1, it: privateKey.publicKey.x963Representation.kotlinByteArray)!
self.keyId = jsonWebKey.keyId!
self.jwsAlgorithm = .es256
self.certificateChain = []
}
public func decrypt(key: KotlinByteArray, iv: KotlinByteArray, aad: KotlinByteArray, input: KotlinByteArray, authTag: KotlinByteArray, algorithm: JweEncryption) async throws -> KmmResult<KotlinByteArray> {
switch algorithm {
case .a256gcm:
let key = SymmetricKey(data: key.data)
guard let nonce = try? AES.GCM.Nonce(data: iv.data),
let sealedBox = try? AES.GCM.SealedBox(nonce: nonce, ciphertext: input.data, tag: authTag.data),
let decryptedData = try? AES.GCM.open(sealedBox, using: key, authenticating: aad.data) else {
return KmmResultFailure(KotlinThrowable(message: "Error in AES.GCM.open"))
}
return KmmResultSuccess(decryptedData.kotlinByteArray)
default:
return KmmResultFailure(KotlinThrowable(message: "Algorithm unknown \(algorithm)"))
}
}
public func encrypt(key: KotlinByteArray, iv: KotlinByteArray, aad: KotlinByteArray, input: KotlinByteArray, algorithm: JweEncryption) -> KmmResult<AuthenticatedCiphertext> {
switch algorithm {
case .a256gcm:
let key = SymmetricKey(data: key.data)
guard let nonce = try? AES.GCM.Nonce(data: iv.data),
let encryptedData = try? AES.GCM.seal(input.data, using: key, nonce: nonce, authenticating: aad.data) else {
return KmmResultFailure(KotlinThrowable(message: "Error in AES.GCM.seal"))
}
let ac = AuthenticatedCiphertext(ciphertext: encryptedData.ciphertext.kotlinByteArray, authtag: encryptedData.tag.kotlinByteArray)
return KmmResultSuccess(ac)
default:
return KmmResultFailure(KotlinThrowable(message: "Algorithm unknown \(algorithm)"))
}
}
public func generateEphemeralKeyPair(ecCurve: EcCurve) -> KmmResult<EphemeralKeyHolder> {
switch ecCurve {
case .secp256R1:
return KmmResultSuccess(VcLibEphemeralKeyHolder())
default:
return KmmResultFailure(KotlinThrowable(message: "ecCurve unknown \(ecCurve)"))
}
}
public func messageDigest(input: KotlinByteArray, digest: VcLibDigest) -> KmmResult<KotlinByteArray> {
switch digest {
case .sha256:
let digest = SHA256.hash(data: input.data)
let data = Data(digest.compactMap { $0 })
return KmmResultSuccess(data.kotlinByteArray)
default:
return KmmResultFailure(KotlinThrowable(message: "Digest unknown \(digest)"))
}
}
public func performKeyAgreement(ephemeralKey: EphemeralKeyHolder, recipientKey: JsonWebKey, algorithm: JweAlgorithm) -> KmmResult<KotlinByteArray> {
switch algorithm {
case .ecdhEs:
let recipientKeyBytes = recipientKey.toAnsiX963ByteArray()
if let throwable = recipientKeyBytes.exceptionOrNull() {
return KmmResultFailure(throwable)
}
guard let recipientKeyBytesValue = recipientKeyBytes.getOrNull(),
let recipientKey = try? P256.KeyAgreement.PublicKey(x963Representation: recipientKeyBytesValue.data),
let ephemeralKey = ephemeralKey as? VcLibEphemeralKeyHolder,
let sharedSecret = try? ephemeralKey.privateKey.sharedSecretFromKeyAgreement(with: recipientKey) else {
return KmmResultFailure(KotlinThrowable(message: "Error in KeyAgreement"))
}
let data = sharedSecret.withUnsafeBytes {
return Data(Array($0))
}
return KmmResultSuccess(data.kotlinByteArray)
default:
return KmmResultFailure(KotlinThrowable(message: "Algorithm unknown \(algorithm)"))
}
}
public func performKeyAgreement(ephemeralKey: JsonWebKey, algorithm: JweAlgorithm) -> KmmResult<KotlinByteArray> {
switch algorithm {
case .ecdhEs:
guard let privateKey = keyChainService.loadPrivateKey() else {
return KmmResultFailure(KotlinThrowable(message: "Could not load private key"))
}
let ephemeralKeyBytes = ephemeralKey.toAnsiX963ByteArray()
if let throwable = ephemeralKeyBytes.exceptionOrNull() {
return KmmResultFailure(throwable)
}
guard let recipientKeyBytesValue = ephemeralKeyBytes.getOrNull(),
let recipientKey = try? P256.KeyAgreement.PublicKey(x963Representation: recipientKeyBytesValue.data),
let privateAgreementKey = try? SecureEnclave.P256.KeyAgreement.PrivateKey(dataRepresentation: privateKey.dataRepresentation),
let sharedSecret = try? privateAgreementKey.sharedSecretFromKeyAgreement(with: recipientKey) else {
return KmmResultFailure(KotlinThrowable(message: "Error in KeyAgreement"))
}
let data = sharedSecret.withUnsafeBytes {
return Data(Array($0))
}
return KmmResultSuccess(data.kotlinByteArray)
default:
return KmmResultFailure(KotlinThrowable(message: "Algorithm unknown \(algorithm)"))
}
}
public func sign(input: KotlinByteArray) async throws -> KmmResult<KotlinByteArray> {
guard let privateKey = keyChainService.loadPrivateKey() else {
return KmmResultFailure(KotlinThrowable(message: "Could not load private key"))
}
guard let signature = try? privateKey.signature(for: input.data) else {
return KmmResultFailure(KotlinThrowable(message: "Signature error"))
}
return KmmResultSuccess(signature.derRepresentation.kotlinByteArray)
}
public func toJsonWebKey() -> JsonWebKey {
return jsonWebKey
}
}
public class VcLibVerifierCryptoService : VerifierCryptoService {
public func verify(input: KotlinByteArray, signature: KotlinByteArray, algorithm: JwsAlgorithm, publicKey: JsonWebKey) -> KmmResult<KotlinBoolean> {
if algorithm != .es256 {
return KmmResultFailure(KotlinThrowable(message: "Can not verify algorithm \(algorithm.name)"))
}
let ansiX963Result = publicKey.toAnsiX963ByteArray()
if let throwable = ansiX963Result.exceptionOrNull() {
return KmmResultFailure(throwable)
}
guard let publicKeyBytes = ansiX963Result.getOrNull(),
let cryptoKitPublicKey = try? P256.Signing.PublicKey(x963Representation: publicKeyBytes.data) else {
return KmmResultFailure(KotlinThrowable(message: "Can not create CryptoKit key"))
}
if let cryptoKitSignature = try? P256.Signing.ECDSASignature(derRepresentation: signature.data) {
let valid = cryptoKitPublicKey.isValidSignature(cryptoKitSignature, for: input.data)
return KmmResultSuccess(KotlinBoolean(value: valid))
} else if let cryptoKitSignature = try? P256.Signing.ECDSASignature(rawRepresentation: signature.data) {
let valid = cryptoKitPublicKey.isValidSignature(cryptoKitSignature, for: input.data)
return KmmResultSuccess(KotlinBoolean(value: valid))
} else {
return KmmResultFailure(KotlinThrowable(message: "Can not read signature"))
}
}
public func extractPublicKeyFromX509Cert(it: KotlinByteArray) -> JsonWebKey? {
guard let certificate = SecCertificateCreateWithData(nil, it.data as CFData),
let publicKey = SecCertificateCopyKey(certificate),
let publicKeyData = SecKeyCopyExternalRepresentation(publicKey, nil) as? Data else {
return nil
}
return JsonWebKey.companion.fromAnsiX963Bytes(type: .ec, curve: .secp256R1, it: publicKeyData.kotlinByteArray)
}
}
public class VcLibEphemeralKeyHolder : EphemeralKeyHolder {
let privateKey: P256.KeyAgreement.PrivateKey
let publicKey: P256.KeyAgreement.PublicKey
let jsonWebKey: JsonWebKey
public init() {
self.privateKey = P256.KeyAgreement.PrivateKey()
self.publicKey = privateKey.publicKey
self.jsonWebKey = JsonWebKey.companion.fromAnsiX963Bytes(type: .ec, curve: .secp256R1, it: publicKey.x963Representation.kotlinByteArray)!
}
public func toPublicJsonWebKey() -> JsonWebKey {
return jsonWebKey
}
}
func KmmResultFailure<T>(_ error: KotlinThrowable) -> KmmResult<T> where T: AnyObject {
return KmmResult<T>.companion.failure(error: error) as! KmmResult<T>
}
func KmmResultSuccess<T>(_ value: T) -> KmmResult<T> where T: AnyObject {
return KmmResult<T>.companion.success(value: value) as! KmmResult<T>
}
extension Data {
public var kotlinByteArray : KotlinByteArray {
let bytes = self.bytes
let kotlinByteArray = KotlinByteArray(size: Int32(self.count))
for index in 0..<bytes.count {
kotlinByteArray.set(index: Int32(index), value: bytes[index])
}
return kotlinByteArray
}
var bytes: [Int8] {
return self.map { Int8(bitPattern: $0)}
}
}
extension Int8 {
var kotlinByte : KotlinByte {
return KotlinByte(value: self)
}
}
extension KotlinByteArray {
public var data : Data {
var bytes = [UInt8]()
for index in 0..<self.size {
bytes.append(UInt8(bitPattern: self.get(index: index)))
}
return Data(bytes)
}
}
```
## Credentials
A single credential itself is an instance of `CredentialSubject` and has no special meaning attached to it. This library uses atomic attributes in the form of `AtomicAttributeCredential`s, containings a `name`, `value` and `mimeType` to transport generic attributes. The enclosing application needs to interpret an instance of `AtomicAttributeCredential` to display for example the first name of a subject.
Other libraries using this library may subclass `CredentialSubject` and call `LibraryInitializer.registerExtensionLibrary()` to register that extension with this library:
```kotlin
@kotlinx.serialization.Serializable
@kotlinx.serialization.SerialName("YourCredential2023")
class YourCredential : at.asitplus.wallet.lib.data.CredentialSubject {
// custom properties
@SerialName("firstname")
val firstname: String
constructor(id: String, firstname: String) : super(id = id) {
this.firstname = firstname
}
override fun toString(): String {
return "YourCredential(id='$id', firstname='$firstname')"
}
}
at.asitplus.wallet.lib.LibraryInitializer.registerExtensionLibrary(
at.asitplus.wallet.lib.LibraryInitializer.ExtensionLibraryInfo(
credentialScheme = object : at.asitplus.wallet.lib.data.ConstantIndex.CredentialScheme {
override val goalCodeIssue: String = "issue-vc-yourcredential"
override val goalCodeRequestProof: String = "request-proof-yourcredential"
override val credentialDefinitionName: String = "yourcredential"
override val schemaUri: String = "https://example.com/schemas/1.0.0/yourcredential.json"
override val vcType: String = "YourCredential2023"
},
serializersModule = kotlinx.serialization.modules.SerializersModule {
kotlinx.serialization.modules.polymorphic(CredentialSubject::class) {
kotlinx.serialization.modules.subclass(YourCredential::class)
}
},
)
)
```
## Further Development
There are several topic worth considering to extend this library:
- Support for [OpenID for Verifiable Credential Issuance](https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html)
- Extending the implementation for [Self-Issued OpenID Provider v2](https://openid.net/specs/openid-connect-self-issued-v2-1_0.html)
buildscript {
repositories {
gradlePluginPortal()
mavenCentral()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}")
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
tasks.register("clean", Delete::class) {
delete(rootProject.buildDir)
}
plugins {
`kotlin-dsl`
}
repositories {
mavenCentral()
}
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
kotlinOptions {
jvmTarget = "11"
}
}
object Versions {
const val kotlin = "1.8.0"
const val `serialization-json` = "1.4.1"
const val datetime = "0.4.0"
const val kotest = "5.5.4"
const val coroutines = "1.6.4"
const val ktor = "2.2.1"
const val napier = "2.6.1"
const val uuid = "0.5.0"
const val resultlib = "1.5.0-SNAPSHOT"
const val encoding = "1.1.3"
const val okio = "3.2.0"
object Jvm {
const val target = "11"
const val `jose-jwt` = "9.25.6"
const val bcprov = "1.72"
const val json = "20210307"
}
}
#Gradle
org.gradle.jvmargs=-Xmx2048M -Dkotlin.daemon.jvm.options\="-Xmx2048M"
#Kotlin
kotlin.code.style=official
#Android
android.useAndroidX=true
#MPP
kotlin.mpp.enableCInteropCommonization=true
kotlin.mpp.stability.nowarn=true
kotlin.native.binary.memoryModel=experimental
kotlin.native.binary.freezing=disabled
kotlin.native.ignoreDisabledTargets=true
artifactVersion = 1.7.2-SNAPSHOT
File added
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
gradlew 0 → 100755
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
pluginManagement {
repositories {
google()
gradlePluginPortal()
mavenCentral()
}
}
rootProject.name = "vclibrary"
include(":vclib")
\ No newline at end of file
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent
import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFrameworkConfig
import java.io.FileInputStream
import java.util.*
plugins {
kotlin("multiplatform")
kotlin("plugin.serialization") version Versions.kotlin
id("maven-publish")
id("io.kotest.multiplatform") version Versions.kotest
}
/* required for maven publication */
val artifactVersion: String by extra
group = "at.asitplus.wallet"
version = artifactVersion
kotlin {
val xcf = XCFrameworkConfig(project, "VcLibKMM")
ios {
binaries.framework {
baseName = "VcLibKMM"
embedBitcode("bitcode")
xcf.add(this)
}
}
iosSimulatorArm64 {
binaries.framework {
baseName = "VcLibKMM"
embedBitcode("bitcode")
xcf.add(this)
}
}
jvm {
compilations.all {
kotlinOptions {
jvmTarget = Versions.Jvm.target
freeCompilerArgs = listOf(
"-Xjsr305=strict"
)
}
}
testRuns["test"].executionTask.configure {
useJUnitPlatform()
}
}
targets.all {
compilations.all {
kotlinOptions {
freeCompilerArgs = listOf(
"-opt-in=kotlinx.serialization.ExperimentalSerializationApi",
"-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
"-opt-in=kotlin.time.ExperimentalTime",
"-opt-in=kotlin.RequiresOptIn",
)
}
}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.coroutines}")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:${Versions.`serialization-json`}")
implementation("com.benasher44:uuid:${Versions.uuid}")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:${Versions.datetime}")
implementation("io.ktor:ktor-http:${Versions.ktor}")
implementation("io.ktor:ktor-utils:${Versions.ktor}")
implementation("com.squareup.okio:okio:${Versions.okio}")
implementation("io.github.aakira:napier:${Versions.napier}")
api("at.asitplus:kmmresult:${Versions.resultlib}")
api("io.matthewnelson.kotlin-components:encoding-base16:${Versions.encoding}")
api("io.matthewnelson.kotlin-components:encoding-base64:${Versions.encoding}")
}
}
val commonTest by getting {
dependencies {
implementation("io.kotest:kotest-assertions-core:${Versions.kotest}")
implementation("io.kotest:kotest-common:${Versions.kotest}")
implementation("io.kotest:kotest-property:${Versions.kotest}")
implementation("io.kotest:kotest-framework-engine:${Versions.kotest}")
implementation("io.kotest:kotest-framework-datatest:${Versions.kotest}")
}
}
val iosMain by getting
val iosSimulatorArm64Main by getting { dependsOn(iosMain) }
val jvmMain by getting {
dependencies {
implementation("org.bouncycastle:bcprov-jdk18on:${Versions.Jvm.bcprov}")
}
}
val jvmTest by getting {
dependencies {
implementation("com.nimbusds:nimbus-jose-jwt:${Versions.Jvm.`jose-jwt`}")
implementation("io.kotest:kotest-runner-junit5-jvm:${Versions.kotest}")
implementation("org.json:json:${Versions.Jvm.json}")
}
}
}
}
tasks.withType<Test> {
if(name == "testReleaseUnitTest") return@withType
useJUnitPlatform()
filter {
isFailOnNoMatchingTests = false
}
testLogging {
showExceptions = true
showStandardStreams = true
events = setOf(
TestLogEvent.FAILED,
TestLogEvent.PASSED
)
exceptionFormat = TestExceptionFormat.FULL
}
}
Properties().apply {
kotlin.runCatching { load(FileInputStream(project.rootProject.file("local.properties"))) }
forEach { (k, v) -> extra.set(k as String, v) }
}
repositories {
mavenLocal()
mavenCentral()
}
publishing {
repositories {
mavenLocal()
}
}
package at.asitplus.wallet.lib
import kotlin.experimental.and
import kotlin.experimental.inv
import kotlin.experimental.or
private fun getByteIndex(i: Long) = (i / 8).toInt()
private fun getBitIndex(i: Long) = (i % 8).toInt()
private fun List<Byte>.getBit(index: Long): Boolean =
if (index < 0) throw IndexOutOfBoundsException("index = $index")
else kotlin.runCatching {
this[getByteIndex(index)].getBit(getBitIndex(index))
}.getOrElse { false }
private fun Byte.getBit(index: Int): Boolean =
if (index < 0 || index > 7) throw IndexOutOfBoundsException("bit index $index out of bounds.")
else (((1 shl index).toByte() and this) != 0.toByte())
/**
* Pure Kotlin Bit Set created by throwing a bunch of extension functions at a MutableList<Byte>
*/
class KmmBitSet constructor(private val bytes: MutableList<Byte>) {
constructor(nbits: Long = 0) : this(
if (nbits < 0) throw IllegalArgumentException("a bit set of size $nbits makes no sense")
else
MutableList(getByteIndex(nbits) + 1) { 0.toByte() })
operator fun get(index: Long): Boolean = bytes.getBit(index)
fun nextSetBit(fromIndex: Long): Long {
if (fromIndex < 0) throw IndexOutOfBoundsException("fromIndex = $fromIndex")
val byteIndex = getByteIndex(fromIndex)
if (byteIndex >= bytes.size) return -1
else {
bytes.subList(byteIndex, bytes.size).let { list ->
val startIndex = getBitIndex(fromIndex).toLong()
for (i: Long in startIndex until list.size.toLong() * 8L) {
if (list.getBit(i)) return byteIndex.toLong() * 8L + i
}
}
return -1
}
}
operator fun set(index: Long, value: Boolean) {
val byteIndex = getByteIndex(index)
while (bytes.size <= byteIndex) bytes.add(0)
val byte = bytes[byteIndex]
bytes[byteIndex] =
if (value) {
((1 shl getBitIndex(index)).toByte() or byte)
} else
((1 shl getBitIndex(index)).toByte().inv() and byte)
}
fun length(): Long = highestSetIndex() + 1L
fun toByteArray(): ByteArray {
return if (bytes.isEmpty() || highestSetIndex() == -1L) byteArrayOf()
else bytes.subList(0, getByteIndex(highestSetIndex()) + 1).toTypedArray().toByteArray()
}
private fun highestSetIndex(): Long {
for (i: Long in bytes.size.toLong() * 8L - 1L downTo 0L) {
if (bytes.getBit(i)) return i
}
return -1L
}
fun toBitString() = toByteArray().toBitString()
}
fun ByteArray.toBitSet(): KmmBitSet = KmmBitSet(toMutableList())
/**
* Returns a view of this bit set's memory layout.
*
* Note that this representation conflicts with the usual binary representation of a bit-set's
* underlying byte array for the following reason:
*
* Printing a byte array usually shows the MS*Byte* at the right-most position, but each byte's MS*Bit*
* at a byte's individual left-most position, leading to bit and byte indices running in opposing directions.
*
* The string representation returned by this function can simply be interpreted as a list of boolean values
* accessible by a monotonic index running in one direction.
*
* See the following illustration of memory layout vs. bit string:
* ```
* ┌──────────────────────────────┐
* │ │
* │ │ Addr: 2
* │ 0 0 0 0 1 1 0 1 │
* │ ◄─23─22─21─20─19─18─17─16─┐ │
* │ │ │
* ├─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│─ ┤
* │ │ │
* │ ┌─────────────────────────┘ │ Addr: 1
* │ │ 1 0 0 0 1 0 0 0 │
* │ └─15─14─12─12─11─10──9──8─┐ │
* │ │ │
* ├─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│─ ┤
* │ │ │
* │ ┌─────────────────────────┘ │ Addr: 0
* │ │ 1 0 1 1 0 1 1 1 │
* │ └──7──6──5──4──3──2──1──0──────index─◄─
* │ │
* └──────────────────────────────┘
*```
* This leads to the following bit string:
* 11101101 00010001 10110000
*/
fun ByteArray.toBitString(): String =
joinToString(separator = " ") {
it.toUByte().toString(2).reversed().let { str ->
(0 until 8).map { kotlin.runCatching { str[it] }.getOrElse { '0' } }.toCharArray()
.concatToString()
}
}
@file:Suppress("unused")
package at.asitplus.wallet.lib
import at.asitplus.wallet.lib.data.AttributeIndex
import at.asitplus.wallet.lib.data.ConstantIndex
import at.asitplus.wallet.lib.data.registerSerializersModule
import kotlinx.serialization.modules.SerializersModule
/**
* Called by other libraries to extend credentials by subclassing [at.asitplus.wallet.lib.data.CredentialSubject].
*/
object LibraryInitializer {
data class ExtensionLibraryInfo(
/**
* Implementation of [at.asitplus.wallet.lib.data.ConstantIndex.CredentialScheme].
*/
val credentialScheme: ConstantIndex.CredentialScheme,
/**
* Definition of a polymorphic serializers module in this form:
* ```
* kotlinx.serialization.modules.SerializersModule {
* kotlinx.serialization.modules.polymorphic(CredentialSubject::class) {
* kotlinx.serialization.modules.subclass(YourCredential::class)
* }
* }
* ```
*/
val serializersModule: SerializersModule,
)
/**
* Register the extension library with information from [data].
*/
fun registerExtensionLibrary(data: ExtensionLibraryInfo) {
ConstantIndex.Parser.registerGoalCode(data.credentialScheme)
AttributeIndex.registerAttributeType(data.credentialScheme)
registerSerializersModule(data.serializersModule)
}
}
\ No newline at end of file
package at.asitplus.wallet.lib
sealed class VcLibException(message: String, cause: Throwable? = null) : Throwable(message, cause)
class DataSourceProblem(message: String, val details: String? = null, cause: Throwable? = null) :
VcLibException(message, cause)
class AuthenticationError(message: String, cause: Throwable? = null) : VcLibException(message, cause)
package at.asitplus.wallet.lib
interface ZlibService {
fun compress(input: ByteArray): ByteArray?
fun decompress(input: ByteArray): ByteArray?
}
expect class DefaultZlibService() : ZlibService
\ No newline at end of file
package at.asitplus.wallet.lib.agent
import at.asitplus.KmmResult
import at.asitplus.wallet.lib.jws.EcCurve
import at.asitplus.wallet.lib.jws.JsonWebKey
import at.asitplus.wallet.lib.jws.JweAlgorithm
import at.asitplus.wallet.lib.jws.JweEncryption
import at.asitplus.wallet.lib.jws.JwsAlgorithm
interface CryptoService {
suspend fun sign(input: ByteArray): KmmResult<ByteArray>
fun encrypt(
key: ByteArray,
iv: ByteArray,
aad: ByteArray,
input: ByteArray,
algorithm: JweEncryption
): KmmResult<AuthenticatedCiphertext>
suspend fun decrypt(
key: ByteArray,
iv: ByteArray,
aad: ByteArray,
input: ByteArray,
authTag: ByteArray,
algorithm: JweEncryption
): KmmResult<ByteArray>
fun generateEphemeralKeyPair(ecCurve: EcCurve): KmmResult<EphemeralKeyHolder>
fun performKeyAgreement(
ephemeralKey: EphemeralKeyHolder,
recipientKey: JsonWebKey,
algorithm: JweAlgorithm
): KmmResult<ByteArray>
fun performKeyAgreement(ephemeralKey: JsonWebKey, algorithm: JweAlgorithm): KmmResult<ByteArray>
fun messageDigest(input: ByteArray, digest: Digest): KmmResult<ByteArray>
val keyId: String
val jwsAlgorithm: JwsAlgorithm
fun toJsonWebKey(): JsonWebKey
}
interface VerifierCryptoService {
fun verify(
input: ByteArray,
signature: ByteArray,
algorithm: JwsAlgorithm,
publicKey: JsonWebKey
): KmmResult<Boolean>
fun extractPublicKeyFromX509Cert(it: ByteArray): JsonWebKey?
}
data class AuthenticatedCiphertext(val ciphertext: ByteArray, val authtag: ByteArray) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as AuthenticatedCiphertext
if (!ciphertext.contentEquals(other.ciphertext)) return false
if (!authtag.contentEquals(other.authtag)) return false
return true
}
override fun hashCode(): Int {
var result = ciphertext.contentHashCode()
result = 31 * result + authtag.contentHashCode()
return result
}
}
interface EphemeralKeyHolder {
fun toPublicJsonWebKey(): JsonWebKey
}
expect class DefaultCryptoService() : CryptoService
expect class DefaultVerifierCryptoService() : VerifierCryptoService
package at.asitplus.wallet.lib.agent
enum class Digest {
SHA256;
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment