From 110115209af05babb068cc8b87970681582f9fa0 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 7 Dec 2022 17:02:17 +0100 Subject: [PATCH] [jsontlv] Add a prefix for octet strings encoded as base64 (#23889) --- src/lib/support/jsontlv/TlvJson.cpp | 12 ++++++++++-- src/lib/support/tests/TestTlvToJson.cpp | 8 ++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/lib/support/jsontlv/TlvJson.cpp b/src/lib/support/jsontlv/TlvJson.cpp index e7044da118f0b0..9b9bc3c25cdb55 100644 --- a/src/lib/support/jsontlv/TlvJson.cpp +++ b/src/lib/support/jsontlv/TlvJson.cpp @@ -67,6 +67,9 @@ struct KeyContext // static constexpr uint16_t kMaxStringLen = 1280; +constexpr const char kBase64Header[] = "base64:"; +constexpr size_t kBase64HeaderLen = ArraySize(kBase64Header) - 1; + namespace chip { /* @@ -152,10 +155,15 @@ CHIP_ERROR TlvToJson(TLV::TLVReader & reader, KeyContext context, Json::Value & VerifyOrReturnError(span.size() < kMaxStringLen, CHIP_ERROR_INVALID_TLV_ELEMENT); Platform::ScopedMemoryBuffer byteString; - byteString.Alloc(BASE64_ENCODED_LEN(span.size()) + 1); + byteString.Alloc(kBase64HeaderLen + BASE64_ENCODED_LEN(span.size()) + 1); VerifyOrReturnError(byteString.Get() != nullptr, CHIP_ERROR_NO_MEMORY); - auto encodedLen = Base64Encode(span.data(), span.size(), byteString.Get()); + auto encodedLen = Base64Encode(span.data(), span.size(), byteString.Get() + kBase64HeaderLen); + if (encodedLen) + { + memcpy(byteString.Get(), kBase64Header, kBase64HeaderLen); + encodedLen += kBase64HeaderLen; + } byteString.Get()[encodedLen] = '\0'; InsertKeyValue(parent, context, byteString.Get()); diff --git a/src/lib/support/tests/TestTlvToJson.cpp b/src/lib/support/tests/TestTlvToJson.cpp index 07e06ca108782b..f2a777a7258716 100644 --- a/src/lib/support/tests/TestTlvToJson.cpp +++ b/src/lib/support/tests/TestTlvToJson.cpp @@ -147,7 +147,7 @@ void TestConverter(nlTestSuite * inSuite, void * inContext) ByteSpan byteSpan(byteBuf); EncodeAndValidate(byteSpan, "{\n" - " \"value\" : \"AQIDBP/+mYjdzQ==\"\n" + " \"value\" : \"base64:AQIDBP/+mYjdzQ==\"\n" "}\n"); DataModel::Nullable nullValue; @@ -170,7 +170,7 @@ void TestConverter(nlTestSuite * inSuite, void * inContext) " \"0\" : 20,\n" " \"1\" : true,\n" " \"2\" : 0,\n" - " \"3\" : \"AQIDBP/+mYjdzQ==\",\n" + " \"3\" : \"base64:AQIDBP/+mYjdzQ==\",\n" " \"4\" : \"hello\",\n" " \"5\" : 0,\n" " \"6\" : 1.0,\n" @@ -200,7 +200,7 @@ void TestConverter(nlTestSuite * inSuite, void * inContext) " \"0\" : 20,\n" " \"1\" : true,\n" " \"2\" : 0,\n" - " \"3\" : \"AQIDBP/+mYjdzQ==\",\n" + " \"3\" : \"base64:AQIDBP/+mYjdzQ==\",\n" " \"4\" : \"hello\",\n" " \"5\" : 0,\n" " \"6\" : 1.0,\n" @@ -210,7 +210,7 @@ void TestConverter(nlTestSuite * inSuite, void * inContext) " \"0\" : 20,\n" " \"1\" : true,\n" " \"2\" : 0,\n" - " \"3\" : \"AQIDBP/+mYjdzQ==\",\n" + " \"3\" : \"base64:AQIDBP/+mYjdzQ==\",\n" " \"4\" : \"hello\",\n" " \"5\" : 0,\n" " \"6\" : 1.0,\n"