Skip to content

CBOR @ValueTags is not encoded with primitive types #3198

Description

@jksiezni

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:

  1. Encode primitive data and prepend encoded tag bytes manually
  2. 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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions