Describe the bug
With current implementation it is not possible to easily encode plain primitives with CBOR tags.
The existing CBOR encoder only applies tags to structures, but there are use cases where a primitive type, like ByteArray, could also be tagged.
For instance, some specifications, such as ISO 18013-5, require a signature of a tagged CBOR byte string. One such example is DeviceAuthenticationBytes:
DeviceAuthenticationBytes = #6.24(bstr .cbor DeviceAuthentication)
To Reproduce
To encode a tagged primitive a value class could be utilized, however it does not pick up @ValueTags annotation at all:
@JvmInline
@Serializable
value class Tagged(
@ByteString
@ValueTags(CborTag.CBOR_ENCODED_DATA) // <- not applied for encoding
val value: ByteArray
)
@Test
fun test() {
assertEquals("d8184101", Cbor.encodeToHexString(Tagged(byteArrayOf(1))))
}
Expected behavior
Be able to encode primitive data with tags, by either providing your own value class definition:
Cbor.encodeToByteArray(Tagged(data))
or by providing a customized serialization strategy:
Cbor.encodeToByteArray(taggedSerializer(CborTag.CBOR_ENCODED_DATA), data)
*** Workaround ***
There are two workarounds possible for current library version:
- Encode primitive data and prepend encoded tag bytes manually
- Encode a
@CborArray annotated class with tagged parameter and truncate encoded result by 1 byte:
@CborArray
@Serializable
class Tagged(
@ByteString
@ValueTags(CborTag.CBOR_ENCODED_DATA)
val item: ByteArray
)
fun Cbor.encodeTaggedToByteArray(byteString: ByteArray): ByteArray {
val encoded = encodeToByteArray(Tagged(byteString))
return encoded.drop(1).toByteArray()
}
Environment
- Kotlin version: 2.3.20
- Library version: 1.11.0
- Kotlin platforms: JVM
Describe the bug
With current implementation it is not possible to easily encode plain primitives with CBOR tags.
The existing CBOR encoder only applies tags to structures, but there are use cases where a primitive type, like ByteArray, could also be tagged.
For instance, some specifications, such as ISO 18013-5, require a signature of a tagged CBOR byte string. One such example is
DeviceAuthenticationBytes:To Reproduce
To encode a tagged primitive a
value classcould be utilized, however it does not pick up@ValueTagsannotation at all:Expected behavior
Be able to encode primitive data with tags, by either providing your own
value classdefinition:or by providing a customized serialization strategy:
*** Workaround ***
There are two workarounds possible for current library version:
@CborArrayannotated class with tagged parameter and truncate encoded result by 1 byte:Environment