Skip to content

Commit

Permalink
Merge pull request #690 from walt-id/keymanager-java-wrapper
Browse files Browse the repository at this point in the history
Make it easier to register key type in KeyManager from Java
  • Loading branch information
waltkb authored Aug 12, 2024
2 parents 024eeec + 1d66cca commit 2ee2b08
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ data class KeyGenerationRequest(
val keyType: KeyType = KeyType.Ed25519,

var config: JsonObject? = null,
)
) {
fun getConfigAsMap() = config?.toMap() ?: emptyMap()
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,15 @@ object KeyManager {
}
}

fun registerByType(type: KType, typeId: String, createFunction: suspend (KeyGenerationRequest) -> Key) {
types[typeId] = type
keyTypeGeneration[typeId] = createFunction
}

inline fun <reified T : Key> register(typeId: String, noinline createFunction: suspend (KeyGenerationRequest) -> T) {
keyManagerLogger().trace { "Registering key type \"$typeId\" to ${T::class.simpleName}..." }
val type = typeOf<T>()
types[typeId] = type
keyTypeGeneration[typeId] = createFunction
registerByType(type, typeId, createFunction)
}

suspend fun createKey(generationRequest: KeyGenerationRequest): Key {
Expand All @@ -59,7 +63,8 @@ object KeyManager {
Json.decodeFromJsonElement(serializer(type), JsonObject(fields)) as Key
}?.apply { init() } ?: error("No type in serialized key")

fun resolveSerializedKeyBlocking(jsonString: String) = resolveSerializedKeyBlocking(json = Json.parseToJsonElement(jsonString).jsonObject)
fun resolveSerializedKeyBlocking(jsonString: String) =
resolveSerializedKeyBlocking(json = Json.parseToJsonElement(jsonString).jsonObject)

}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package id.walt.crypto.keys

import kotlin.jvm.internal.Reflection

object KeyManagerJavaExtensions {

/**
* Use like this from Java:
* ```
* KeyManagerJavaExtensions.INSTANCE.register(MyJavaBasedKey.class, "theTypeId",
* keyGenerationRequest -> {
* String backend = keyGenerationRequest.getBackend();
* KeyType keyType = keyGenerationRequest.getKeyType();
*
* // Return key here
* return null;
* }
* );
* ```
*/
fun register(javaClass: Class<out Key>, typeId: String, createFunction: (KeyGenerationRequest) -> Key) =
KeyManager.registerByType(
type = Reflection.typeOf(javaClass),
typeId = typeId,
createFunction = createFunction
)

}

0 comments on commit 2ee2b08

Please sign in to comment.