Revert back cbor related patches. 97/5897/6
authorleechul <chuls.lee@samsung.com>
Tue, 15 Mar 2016 05:34:34 +0000 (14:34 +0900)
committerRandeep Singh <randeep.s@samsung.com>
Tue, 15 Mar 2016 14:24:50 +0000 (14:24 +0000)
[Patch #1] Intial upload.
[Patch #2] Modify provisionig sample's SConscript to ignore sample codes in case of tizen.
             * The json file will be copied in case of tizen.
[Patch #3] Remove the segmentation fault in debug mode.
[Patch #4] Modify the build script to not include security samples in case of tizen build.
[Patch #5] Revmoe the printf

Change-Id: I88b9b5b68bc641f219bcf0c26dbf1dd4c61ae177
Signed-off-by: leechul <chuls.lee@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/5897
Reviewed-by: Jongsung Lee <js126.lee@samsung.com>
Reviewed-by: dongik Lee <dongik.lee@samsung.com>
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Randeep Singh <randeep.s@samsung.com>
73 files changed:
oic_svr_db.dat [deleted file]
oic_svr_db.json [deleted file]
resource/csdk/security/SConscript
resource/csdk/security/include/base64.h
resource/csdk/security/include/internal/aclresource.h
resource/csdk/security/include/internal/amaclresource.h [changed mode: 0755->0644]
resource/csdk/security/include/internal/amsmgr.h
resource/csdk/security/include/internal/credresource.h
resource/csdk/security/include/internal/crlresource.h
resource/csdk/security/include/internal/doxmresource.h
resource/csdk/security/include/internal/policyengine.h
resource/csdk/security/include/internal/psinterface.h
resource/csdk/security/include/internal/pstatresource.h
resource/csdk/security/include/internal/resourcemanager.h
resource/csdk/security/include/internal/secureresourcemanager.h
resource/csdk/security/include/internal/security_internals.h [deleted file]
resource/csdk/security/include/internal/srmresourcestrings.h
resource/csdk/security/include/internal/svcresource.h
resource/csdk/security/include/pbkdf2.h
resource/csdk/security/include/pinoxmcommon.h
resource/csdk/security/include/securevirtualresourcetypes.h
resource/csdk/security/include/srmutility.h
resource/csdk/security/provisioning/SConscript
resource/csdk/security/provisioning/include/internal/ownershiptransfermanager.h
resource/csdk/security/provisioning/include/oxm/oxmjustworks.h
resource/csdk/security/provisioning/include/oxm/oxmrandompin.h
resource/csdk/security/provisioning/sample/SConscript
resource/csdk/security/provisioning/src/credentialgenerator.c
resource/csdk/security/provisioning/src/ownershiptransfermanager.c
resource/csdk/security/provisioning/src/oxmjustworks.c
resource/csdk/security/provisioning/src/oxmrandompin.c
resource/csdk/security/provisioning/src/pmutility.c
resource/csdk/security/provisioning/src/secureresourceprovider.c
resource/csdk/security/provisioning/unittest/otmunittest.cpp
resource/csdk/security/src/aclresource.c
resource/csdk/security/src/amaclresource.c
resource/csdk/security/src/amsmgr.c
resource/csdk/security/src/base64.c
resource/csdk/security/src/credresource.c
resource/csdk/security/src/crlresource.c
resource/csdk/security/src/directpairing.c
resource/csdk/security/src/doxmresource.c
resource/csdk/security/src/dpairingresource.c [changed mode: 0755->0644]
resource/csdk/security/src/oxmpincommon.c
resource/csdk/security/src/pbkdf2.c
resource/csdk/security/src/policyengine.c
resource/csdk/security/src/psinterface.c
resource/csdk/security/src/pstatresource.c
resource/csdk/security/src/resourcemanager.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/src/srmresourcestrings.c
resource/csdk/security/src/srmutility.c
resource/csdk/security/src/svcresource.c
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/aclresourcetest.cpp
resource/csdk/security/unittest/amaclresourcetest.cpp [deleted file]
resource/csdk/security/unittest/credentialresource.cpp
resource/csdk/security/unittest/doxmresource.cpp
resource/csdk/security/unittest/oic_unittest.dat [deleted file]
resource/csdk/security/unittest/oic_unittest_acl1.dat [deleted file]
resource/csdk/security/unittest/oic_unittest_acl1.json
resource/csdk/security/unittest/oic_unittest_default_acl.dat [deleted file]
resource/csdk/security/unittest/oic_unittest_default_acl.json
resource/csdk/security/unittest/pstatresource.cpp
resource/csdk/security/unittest/srmtestcommon.cpp
resource/csdk/security/unittest/srmtestcommon.h
resource/csdk/security/unittest/svcresourcetest.cpp
resource/csdk/stack/include/ocpayload.h [changed mode: 0755->0644]
resource/csdk/stack/include/octypes.h
resource/csdk/stack/src/ocpayload.c [changed mode: 0755->0644]
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c [changed mode: 0755->0644]
resource/provisioning/SConscript [changed mode: 0755->0644]

diff --git a/oic_svr_db.dat b/oic_svr_db.dat
deleted file mode 100644 (file)
index 62fc7db..0000000
Binary files a/oic_svr_db.dat and /dev/null differ
diff --git a/oic_svr_db.json b/oic_svr_db.json
deleted file mode 100644 (file)
index 7f8b100..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-{
-  "acl": "gaRnc3ViAHJzckEqZ3JzcmMAYW2IaC9vaWMvcmVzZi9vaWMvZGYvb2ljL3BwL29pYy9yZXMvdHlwZXMvZGcvb2ljL2FkbC9vaWMvc2VjL2FjbG0vb2ljL3NlYy9kb3htbi9vaWMvc2VjL3BzdGF0Z3Blcm1zAG8CZ293bnJzAG-BUDIyMjIyMjIyMjIyMjIyMjI"
-}
index 04a98db..f2aed83 100644 (file)
@@ -145,3 +145,4 @@ libocsrm_env.InstallTarget(libocsrm, 'libocsrm')
 
 if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
        SConscript('provisioning/SConscript')
+
index a983f1e..4d5837d 100644 (file)
@@ -1,22 +1,22 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ /******************************************************************
+  *
+  * Copyright 2015 Samsung Electronics All Rights Reserved.
+  *
+  *
+  *
+  * 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.
+  *
+  ******************************************************************/
 
 #ifndef _IOTVT_B64_H_
 #define _IOTVT_B64_H_
@@ -41,27 +41,27 @@ extern "C" {
 #define B64DECODE_OUT_SAFESIZE(x) (((x)*3)/4)
 
 /**
- * Result code of base64 functions.
+ * Result code of base64 functions
  */
-typedef enum
-{
+typedef enum {
     B64_OK = 0,
     B64_INVALID_PARAM,
     B64_OUTPUT_BUFFER_TOO_SMALL,
     B64_ERROR
-} B64Result;
+}B64Result;
 
 /**
  * Encode the plain message in base64.
  *
- * @param in is the plain message to be converted.
- * @param inLen is the byte length of plain message.
- * @param outBuf is the output buffer containing Base64 encoded message.
- * @note outBuf adds a NULL to the string configuration.
- * @param outBufSize is the size of output buffer.
- * @param outLen is the byte length of encoded message.
+ * @param[in] in  Plain message
+ * @param[in] inLen  Byte length of 'in'
+ * @param[in,out] outBuf Output buffer
+ *                Base64 encoded message will be written into 'outBuf'
+ *                NOTE : This method adds a NULL to the string configuration
+ * @param[in] outBufSize Size of output buffer
+ * @param[out] outLen  Byte length of encoded message
  *
- * @return ::B64_OK for Success, otherwise some error value.
+ * @return  B64_OK for Success, otherwise some error value
  */
 B64Result b64Encode(const uint8_t* in, const size_t inLen,
                char* outBuf, const size_t outBufSize, uint32_t *outLen);
@@ -69,14 +69,14 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 /**
  * Decode the encoded message in base64.
  *
- * @param in is the Base64 encoded message to be converted.
- * @param inLen is the byte length of the encoded message.
- * @param outBuf is the output buffer containing decoded message.
- * @note outBuf adds a NULL to the string configuration.
- * @param outBufSize is the size of output buffer.
- * @param outLen is the byte length of decoded message.
+ * @param[in] in  Base64 encoded message
+ * @param[in] inLen  Byte lenth of 'in'
+ * @param[in, out] outBuf  Output buffer
+ *                 Base64 decoded message will be written into 'outBuf'
+ * @param[in] outBufSize Size of output buffer
+ * @param[out] outLen  Byte length of decoded message
  *
- * @return ::B64_OK for Success, otherwise some error value.
+ * @return  B64_OK for Success, otherwise some error value
  */
 B64Result b64Decode(const char* in, const size_t inLen,
                uint8_t* outBuf, size_t outBufSize, uint32_t *outLen);
index 97c6716..ccd97ef 100644 (file)
@@ -28,15 +28,16 @@ extern "C" {
 /**
  * Initialize ACL resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitACLResource();
 
 /**
  * Perform cleanup for ACL resources.
  *
+ * @retval  none
  */
-OCStackResult DeInitACLResource();
+void DeInitACLResource();
 
 /**
  * This method is used by PolicyEngine to retrieve ACL for a Subject.
@@ -45,39 +46,38 @@ OCStackResult DeInitACLResource();
  * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
  *                successive calls for same subjectId.
  *
- * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL.
+ * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
  *
- * @return reference to @ref OicSecAcl_t if ACL is found, else NULL.
+ * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL
  */
 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr);
 
 /**
- * This function converts ACL data into CBOR format.
+ * This function converts ACL data into JSON format.
+ * Caller needs to invoke 'free' when done using
+ * returned string.
+ * @param acl  instance of OicSecAcl_t structure.
  *
- * @param acl instance of @ref OicSecAcl_t structure.
- * @param outPayload is the pointer to allocated memory for cbor payload.
- * @param size of the cbor payload.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  pointer to ACL in json format.
  */
-OCStackResult AclToCBORPayload(const OicSecAcl_t * acl, uint8_t **outPayload, size_t *size);
+char* BinToAclJSON(const OicSecAcl_t * acl);
+
 
 /**
  * This function deletes ACL data.
  *
- * @param acl instance of @ref OicSecAcl_t structure to be deleted.
+ * @param acl  instance of OicSecAcl_t structure.
  */
 void DeleteACLList(OicSecAcl_t* acl);
 
+
 /**
  * This function installs a new ACL.
+ * @param newJsonStr JSON string representing a new ACL.
  *
- * @param payload cbor value representing a new ACL.
- * @param size of the cbor payload.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
-OCStackResult InstallNewACL(const uint8_t* payload, const size_t size);
+OCStackResult InstallNewACL(const char* newJsonStr);
 
 /**
  * This function updates default ACL which is required for ownership transfer.
@@ -92,3 +92,5 @@ OCStackResult UpdateDefaultSecProvACL();
 #endif
 
 #endif //IOTVT_SRM_ACLR_H
+
+
old mode 100755 (executable)
new mode 100644 (file)
index e3dc1fa..9c37a0e
@@ -36,12 +36,14 @@ extern "C" {
 /**
  * Initialize Amacl resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitAmaclResource();
 
 /**
  * Perform cleanup for Amacl resources.
+ *
+ * @retval  none
  */
 void DeInitAmaclResource();
 
@@ -50,31 +52,30 @@ void DeInitAmaclResource();
  * If the Amacl is found for the given resource then populate the parameter
  * amsId with Amacl resource amss id.
  *
- * @param resource for which AMS service is required.
- * @param amsId of the ams service for the given resource.
+ * @param resource  resource for which AMS service is required.
+ * @param amsId     ID of the ams service for the given resource
+ *
+ * @retval
+ *  OC_STACK_OK     If Amacl found for the resource
+ *  OC_STACK_ERROR  If no Amacl found for the resource
  *
- * @return ::OC_STACK_OK, if Amacl is found for the resource, else ::OC_STACK_ERROR,
- *  if no Amacl found for the resource.
  */
 OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsId);
 
 /**
- * This function converts Amacl data into CBOR format.
- * Caller needs to invoke 'free' when done using returned string.
- *
- * @param amacl instance of @ref OicSecAmacl_t structure.
- * @param cborPayload is the converted cbor value of @ref OicSecAmacl_t structure.
- * @param cborSize is the size of the cbor payload. This value is the size of the
- * cborPayload. It should not be NON-NULL value.
+ * This function converts Amacl data into JSON format.
+ * Caller needs to invoke 'free' when done using
+ * returned string.
+ * @param Amacl  instance of OicSecAmacl_t structure.
  *
- * @return ::OC_STACK_OK for Success. ::OC_STACK_INVALID in case of invalid parameters.
- * ::OC_STACK_ERROR in case of error in converting to cbor.
+ * @retval  pointer to Amacl in json format.
  */
-OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amacl, uint8_t **cborPayload,
-                                 size_t *cborSize);
+char* BinToAmaclJSON(const OicSecAmacl_t * amacl);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_AMACLR_H
+
+
index e07b442..d9d74b5 100644 (file)
 #ifndef IOTVT_SRM_AMSMGR_H
 #define IOTVT_SRM_AMSMGR_H
 
-#include <stdlib.h>
-#include <stdint.h>
-
 #include "ocstack.h"
 #include "logger.h"
 #include "policyengine.h"
 #include "securevirtualresourcetypes.h"
 #include "cainterface.h"
+#include <stdlib.h>
+#include <stdint.h>
 
 typedef struct PEContext PEContext_t;
 /**
- * The AMS context.
+ * @brief   The AMS context..
  */
 typedef struct AmsMgrContext
 {
@@ -41,95 +40,103 @@ typedef struct AmsMgrContext
     CARequestInfo_t     *requestInfo;
 } AmsMgrContext_t;
 
+
 /**
- * This method updates AmsMgr context's endpoint & requestInfo.
+ * @brief This method updates AmsMgr context's endpoint & requestInfo
  *
- * @param context is the policy engine context.
- * @param endpoint is the CA Endpoint info of the requester.
- * @param requestInfo is the CA RequestInfo of the requester.
- *
- * @return ::OC_STACK_OK if successful, else other value in case of error.
+ * @param context          Policy engine context.
+ * @param endpoint         CA Endpoint info of the requester
+ * @param requestInfo      CA RequestInfo of the requester
  */
-OCStackResult UpdateAmsMgrContext(PEContext_t *context,
-                                  const CAEndpoint_t *endpoint,
-                                  const CARequestInfo_t *requestInfo);
+OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
+                       const CARequestInfo_t *requestInfo);
 
 /**
+ *
  * This method is called by PolicyEngine to Discover AMS service.
  * It sends muticast discovery request such as
  * /oic/sec/doxm?deviceid="AMSSrvcDeviceID" to discover AMS service
- * with deviceId="AMSSrvcDeviceID".
+ * with deviceId="AMSSrvcDeviceID"
+ *
+ * @param context   Policy engine context.
  *
- * @param context is the policy engine context.
+ * @retval
+ *  OC_STACK_OK     If able to successfully send multicast discovery request.
+ *  OC_STACK_ERROR  If unable to successfully send multicast discovery request due to error.
  *
- * @return ::OC_STACK_OK,If able to successfully send multicast discovery request.
- * else ::OC_STACK_ERROR, If unable to successfully send multicast discovery request
- * due to error.
  */
 OCStackResult DiscoverAmsService(PEContext_t *context);
 
+
 /**
+ *
  * This method sends unicast request to retrieve the secured port info of the
  * discovered AMS service. It sends unicast discovery request such as
- * /oic/res?rt="oic.sec.doxm" to the discovered AMS service.
+ * /oic/res?rt="oic.sec.doxm" to the discovered AMS service
  *
- * @param context is the policy engine context.
+ * @param context   Policy engine context.
+ *
+ * @retval
+ *  OC_STACK_OK     If able to successfully send unicast discovery request
+ *  OC_STACK_ERROR  If unable to successfully send unicast discovery request due to error
  *
- * @return ::OC_STACK_OK,If able to successfully send unicast discovery request.
- * else ::OC_STACK_ERROR, If unable to successfully send unicast discovery request
- * due to error.
  */
-OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,
-                                             OCDevAddr *devAddr,
-                                             OCConnectivityType connType);
+OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
+                                      OCConnectivityType connType);
+
 
 /**
+ *
  * This method sends unicast request to AMS service to get ACL for
  * the Subject and/or Resource. It sends unicast request such as
  * /oic/sec/acl?sub="subjectId";rsrc="/a/led" to get the ACL for
- * the subject & resource.
+ * the subject & resource
  *
- * @param context is the policy engine context.
+ * @param context   Policy engine context.
  *
- * @return ::OC_STACK_OK, If able to successfully send unicast ACL request.
- * ::OC_STACK_ERROR, If unable to successfully send unicast ACL request due to error.
+ * @retval
+ *  OC_STACK_OK     If able to successfully send unicast ACL request
+ *  OC_STACK_ERROR  If unable to successfully send unicast ACL request due to error
  *
  */
-OCStackResult SendAclReq(PEContext_t *context,
-                         OCDevAddr *devAddr,
-                         OCConnectivityType connType,
-                         uint16_t securedPort);
+OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
+        uint16_t securedPort);
+
 
 /*
- * Cleanup CARequestInfo_t object.
- *
- * @param requestInfo is the pointer to @ref CARequestInfo_t.
+ * Cleanup CARequestInfo_t object
+ * @param requestInfo        pointer to RequestInfo_t object
  */
 void FreeCARequestInfo(CARequestInfo_t *requestInfo);
 
+
 /*
  * This method is used by Policy engine to checks Amacl resource.
  * If Amacl is found then it fills up context->amsMgrContext->amsDeviceId
  * with amsID of the Amacl else leaves it empty.
  *
- * @param context is the policy engine context.
+ * @param context   Policy engine context.
  *
- * @return true, if Amacl for the resource is found. false, if Amacl for the
- * resource is not found
+ * @return          true if AMacl for the resource is found
+ *                  false if AMacl for the resource is not found
  */
 bool FoundAmaclForRequest(PEContext_t *context);
 
+
 /*
- * This method is used by Policy engine to process AMS request.
+ * This method is used by Policy engine to process AMS request
+ *
+ * @param context   Policy engine context.
  *
- * @param context is the policy engine context.
  */
 void ProcessAMSRequest(PEContext_t *context);
 
+
 /*
- * This method is used by Policy engine to free AMS context requestInfo/
+ * This method is used by Policy engine to free AMS context requestInfo
+ *
+ * @param requestInfo   pointer to CARequestInfo_t.
  *
- * @param requestInfo is the pointer to @ref CARequestInfo_t.
  */
 void FreeCARequestInfo(CARequestInfo_t *requestInfo);
 
index a7cad66..74ea373 100644 (file)
@@ -32,42 +32,45 @@ extern "C" {
 /**
  * Initialize credential resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK, if initialization is successful, else ::OC_STACK_ERROR if
- * initialization fails.
+ * @retval
+ *     OC_STACK_OK    - no errors
+ *     OC_STACK_ERROR - stack process error
  */
 OCStackResult InitCredResource();
 
 /**
  * Perform cleanup for credential resources.
  *
- * @return ::OC_STACK_OK, if no errors. ::OC_STACK_ERROR, if stack process error.
- * ::OC_STACK_NO_RESOURCE, if resource not found.
- * ::OC_STACK_INVALID_PARAM, if invalid param.
+ * @retval
+ *     OC_STACK_OK              - no errors
+ *     OC_STACK_ERROR           - stack process error
+ *     OC_STACK_NO_RESOURCE     - resource not found
+ *     OC_STACK_INVALID_PARAM   - invalid param
  */
 OCStackResult DeInitCredResource();
 
 /**
- * This method is used by tinydtls/SRM to retrieve credential for given subject.
+ * This method is used by tinydtls/SRM to retrieve credential for given Subject.
  *
- * @param subjectId for which credential is required.
+ * @param subject - subject for which credential is required.
  *
- * @return reference to @ref OicSecCred_t, if credential is found, else NULL, if credential
- * not found.
+ * @retval
+ *     reference to OicSecCred_t - if credential is found
+ *     NULL                      - if credential not found
  */
 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subjectId);
 
 /**
- * This function converts credential data into CBOR format.
- * Caller needs to invoke 'free' when done using returned string.
- *
- * @param cred is the pointer to instance of OicSecCred_t structure.
- * @param cborPayload is the CBOR converted value.
- * @param cborSize is the size of the CBOR.
- *
- * @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
+ * This function converts credential data into JSON format.
+ * Caller needs to invoke 'free' when done using
+ * returned string.
+ * @param cred  pointer to instance of OicSecCred_t structure.
+ *
+ * @retval
+ *      pointer to JSON credential representation - if credential for subjectId found
+ *      NULL                                      - if credential for subjectId not found
  */
-OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
-                                size_t *cborSize);
+char* BinToCredJSON(const OicSecCred_t* cred);
 
 /**
  * This function generates the bin credential data.
@@ -79,42 +82,53 @@ OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
  * @param ownersLen length of owners array
  * @param owners array of owners.
  *
- * @return pointer to instance of @ref OicSecCred_t if successful. else NULL in case of error.
-
+ * @retval
+ *      pointer to instance of OicSecCred_t  - success
+ *      NULL                                 - error
  */
 OicSecCred_t * GenerateCredential(const OicUuid_t* subject, OicSecCredType_t credType,
-                     const uint8_t * publicData, const uint8_t * privateData,
-                     size_t ownersLen, const OicUuid_t * owners);
+                     const char * publicData, const char * privateData, size_t ownersLen,
+                     const OicUuid_t * owners);
 
 /**
  * This function adds the new cred to the credential list.
  *
- * @param cred is the pointer to new credential.
+ * @param cred pointer to new credential.
  *
- * @return ::OC_STACK_OK, cred not NULL and persistent storage gets updated.
- * ::OC_STACK_ERROR, cred is NULL or fails to update persistent storage.
+ * @retval
+ *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
+ *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
  */
 OCStackResult AddCredential(OicSecCred_t * cred);
 
 /**
  * Function to remove the credential from SVR DB.
  *
- * @param credId is the Credential ID to be deleted.
+ * @param credId Credential ID to be deleted.
  *
- * @return ::OC_STACK_OK for success, or errorcode otherwise.
+ * @return OC_STACK_OK for success and errorcode otherwise.
  */
-OCStackResult RemoveCredential(const OicUuid_t *credId);
+OCStackResult RemoveCredential(const OicUuid_t* credId);
+
+/**
+ * Remove all credential data on credential resource and persistent storage
+ *
+ * @retval
+ *     OC_STACK_OK              - no errors
+ *     OC_STACK_ERROR           - stack process error
+ */
+OCStackResult RemoveAllCredentials(void);
 
 #if defined(__WITH_DTLS__)
 /**
  * This internal callback is used by lower stack (i.e. CA layer) to
  * retrieve PSK credentials from RI security layer.
  *
- * @param type of PSK data required by CA layer during DTLS handshake.
- * @param desc Additional request information.
- * @param desc_len is the actual length of desc.
- * @param result  is must be filled with the requested information.
- * @param result_length is the maximum size of @p result.
+ * @param[in]  type type of PSK data required by CA layer during DTLS handshake.
+ * @param[in]  desc Additional request information.
+ * @param[in]  desc_len The actual length of desc.
+ * @param[out] result  Must be filled with the requested information.
+ * @param[in]  result_length  Maximum size of @p result.
  *
  * @return The number of bytes written to @p result or a value
  *         less than zero on error.
@@ -124,22 +138,21 @@ int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
               unsigned char *result, size_t result_length);
 
 /**
- * Add temporal PSK to PIN based OxM.
+ * Add temporal PSK to PIN based OxM
  *
- * @param tmpSubject is the UUID of target device
- * @param credType is the type of credential to be added
- * @param pin is the numeric characters
- * @param pinSize is the length of 'pin'
- * @param ownersLen is the number of owners
- * @param owners is the array of owners
- * @param tmpCredSubject is the generated credential's subject.
+ * @param[in] tmpSubject UUID of target device
+ * @param[in] credType Type of credential to be added
+ * @param[in] pin numeric characters
+ * @param[in] pinSize length of 'pin'
+ * @param[in] ownersLen Number of owners
+ * @param[in] owners Array of owners
+ * @param[out] tmpCredSubject Generated credential's subject.
  *
- * @return ::OC_STACK_OK for success or else errorcode.
+ * @return OC_STACK_OK for success and errorcode otherwise.
  */
 OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t credType,
                             const char * pin, size_t pinSize,
-                            size_t ownersLen, const OicUuid_t * owners,
-                            OicUuid_t* tmpCredSubject);
+                            size_t ownersLen, const OicUuid_t * owners, OicUuid_t* tmpCredSubject);
 
 #endif /* __WITH_DTLS__ */
 
@@ -147,17 +160,18 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
 /**
  * This function is used toretrieve certificate credentials from RI security layer.
  *
- * @param credInfo is the binary structure containing certificate credentials
+ * @param credInfo
+ *     binary structure containing certificate credentials
  *
- * @return 0 on success.
+ * @retval 0  on scuccess
  */
 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo);
 #endif /*__WITH_X509__*/
 
 /**
- * Function to deallocate allocated memory to OicSecCred_t.
+ * Function to deallocate allocated memory to OicSecCred_t
  *
- * @param cred pointer to cred type.
+ * @param cred pointer to cred type
  *
  */
 void DeleteCredList(OicSecCred_t* cred);
@@ -167,3 +181,5 @@ void DeleteCredList(OicSecCred_t* cred);
 #endif
 
 #endif //IOTVT_SRM_CREDR_H
+
+
index c31143d..75178d8 100644 (file)
@@ -29,46 +29,43 @@ extern "C" {
 #endif
 
 /**
- * This function stores CRL in SRM.
+ * This function stores CRL in SRM
+ * @param crl - CRL
  *
- * @param crl to be stored in SRM.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @returns OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult UpdateCRLResource(const OicSecCrl_t *crl);
 
 /**
- * This function get encoded with base64 CRL from SRM.
- *
- * @note Caller responsible for resulting string memory (use OICFree to remove it).
+ * This function get encoded with base64 CRL from SRM
  *
- * @return encoded CRL with base64 format. NULL if error occured (e.g. CRL did not set).
+ * @returns encoded CRL with base64 format. NULL if error occured (e.g. CRL did not set)
+ * @note Caller responsible for resulting string memory (use OICFree to remove it)
  */
 char* GetBase64CRL();
 /**
- * This function get encoded with DER CRL from SRM.
+ * This function get encoded with DER CRL from SRM
  *
- * @return encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set).
+ * @returns encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set)
  */
 void  GetDerCrl(ByteArray crlArray);
 
 /**
- * This function get CRL from SRM.
+ * This function get CRL from SRM
  *
- * @param crl is a pointer to buffer that contains crl. Shoul be not NULL. Buffer
+ * @param crl [out] - pointer to buffer that contains crl. Shoul be not NULL. Buffer
  * will be allocated by the function and content of *crl will be ignored.
- * @param outlen is a pointer to length of the CRL buffer. Should be not NULL.
+ * @param outlen [out] - pointer to length of the CRL buffer. Shoul be not NULL.
  *
- * @note Caller responsible for crl buffer memory (use OICFree to free it).
- *
- * @return ::OC_STACK_OK if success, otherwise some error value.
+ * @returns OC_STACK_OK if success and errorcode otherwise.
+ * @note Caller responsible for crl buffer memory (use OICFree to free it)
  */
 OicSecCrl_t * JSONToCrlBin(const char * jsonStr);
 
 /**
- * Initialize CRL resource by loading data from persistent storage.
+ * Initialize CLR resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @returns OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitCRLResource();
 
@@ -77,15 +74,15 @@ OCStackResult InitCRLResource();
  */
 void DeInitCRLResource();
 
-/**
- * Get an instance of CRL resource.
- *
- * @return reference to the @ref OicSecCrl_t, holding reference to CRL resource.
- */
 OicSecCrl_t *GetCRLResource();
 
+OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParameter);
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_CRLR_H
+
+
index e9ce684..237da64 100644 (file)
@@ -30,71 +30,67 @@ extern "C" {
 /**
  * Initialize DOXM resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitDoxmResource();
 
 /**
  * Perform cleanup for DOXM resources.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult DeInitDoxmResource();
 
 /**
  * This method is used by SRM to retrieve DOXM resource data..
  *
- * @return reference to @ref OicSecDoxm_t, binary format of Doxm resource data.
+ * @retval  reference to @ref OicSecDoxm_t, binary format of Doxm resource data
  */
 const OicSecDoxm_t* GetDoxmResourceData();
 
 /**
- * This method converts CBOR DOXM into binary DOXM.
- * The CBOR DOXM can be from persistent database or
+ * This method converts JSON DOXM into binary DOXM.
+ * The JSON DOXM can be from persistent database or
  * or received as PUT/POST request.
  *
- * @param cborPayload is a doxm data in cbor.
- * @note Caller needs to invoke OCFree after done using the return pointer.
- * @param doxm is the pointer to @ref OicSecDoxm_t.
- * @param size of the cborPayload. In case value is 0, CBOR_SIZE value is assigned.
+ * @param[in] jsonStr  doxm data in json string.
+ * @return pointer to OicSecDoxm_t.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @note Caller needs to invoke OCFree after done
+ *       using the return pointer
  */
-OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
-                                OicSecDoxm_t **doxm);
+OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr);
 
 /**
- * This method converts DOXM data into CBOR format.
+ * This method converts DOXM data into JSON format.
  * Caller needs to invoke 'free' when finished done using
- * return string.
+ * return string
  *
- * @param doxm Pointer to @ref OicSecDoxm_t.
- * @note Caller needs to invoke OCFree after done using the return pointer.
- * @param cborPayload is the payload of the cbor.
- * @param cborSize is the size of the cbor payload. Passed parameter should not be NULL.
+ * @param[in] doxm  Pointer to OicSecDoxm_t.
+ * @return pointer to json string.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @note Caller needs to invoke OCFree after done
+ *       using the return pointer
  */
-OCStackResult DoxmToCBORPayload(const OicSecDoxm_t * doxm, uint8_t **cborPayload,
-                                size_t *cborSize);
+char * BinToDoxmJSON(const OicSecDoxm_t * doxm);
 
 /**
  * This method returns the SRM device ID for this device.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID);
 
 /**
- * Gets the OicUuid_t value for the owner of this device.
+ * @brief Gets the OicUuid_t value for the owner of this device.
  *
- * @return ::OC_STACK_OK if devOwner is a valid UUID, otherwise ::OC_STACK_ERROR.
+ * @return OC_STACK_OK if devOwner is a valid UUID, otherwise OC_STACK_ERROR.
  */
 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner);
 
 /** This function deallocates the memory for OicSecDoxm_t .
  *
- * @param doxm is the pointer to @ref OicSecDoxm_t.
+ * @param[in] doxm  Pointer to OicSecDoxm_t.
  */
 void DeleteDoxmBinData(OicSecDoxm_t* doxm);
 
@@ -109,3 +105,5 @@ void RestoreDoxmToInitState();
 #endif
 
 #endif //IOTVT_SRM_DOXMR_H
+
+
index 72aa01c..ba40d68 100644 (file)
@@ -31,6 +31,7 @@
 
 typedef struct AmsMgrContext AmsMgrContext_t;
 
+
 typedef enum PEState
 {
     STOPPED = 0,              //Policy engine state machine is not running
@@ -39,6 +40,7 @@ typedef enum PEState
     BUSY                      //Can't process new request as processing other requests
 } PEState_t;
 
+
 typedef struct PEContext
 {
     PEState_t   state;
@@ -54,12 +56,13 @@ typedef struct PEContext
 /**
  * Check whether a request should be allowed.
  *
- * @param context is the pointer to Policy Engine context to use.
- * @param subjectId is the pointer to Id of the requesting entity.
- * @param resource is the pointer to URI of Resource being requested.
- * @param permission is the requested permission.
+ * @param   context     Pointer to Policy Engine context to use.
+ * @param   subjectId   Pointer to Id of the requesting entity.
+ * @param   resource    Pointer to URI of Resource being requested.
+ * @param   permission  Requested permission.
  *
- * @return ::ACCESS_GRANTED if request should go through, otherwise some flavor of ACCESS_DENIED.
+ * @return  ACCESS_GRANTED if request should go through,
+ *          otherwise some flavor of ACCESS_DENIED
  */
 SRMAccessResponse_t CheckPermission(
     PEContext_t     *context,
@@ -71,35 +74,33 @@ SRMAccessResponse_t CheckPermission(
  * Initialize the Policy Engine. Call this before calling CheckPermission().
  * TODO Eventually this and DeInit() need to be called from a new
  *      "SRMInit(SRMContext_t *)" function, TBD after BeachHead.
- * @param context is the pointer to Policy Engine context to initialize.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @param   context     Pointer to Policy Engine context to initialize.
+ * @return  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitPolicyEngine(PEContext_t *context);
 
 /**
  * De-Initialize the Policy Engine. Call this before exiting to allow Policy
  * Engine to do cleanup on context.
- *
- * @param context is the pointer to Policy Engine context to de-initialize.
+ * @param   context     Pointer to Policy Engine context to de-initialize.
+ * @return  none
  */
 void DeInitPolicyEngine(PEContext_t *context);
 
 /**
- * Get CRUDN permission for a method.
- *
- * @param method is CRUDN permission being seeked.
- *
- * @return the uint16_t CRUDN permission .
+ * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
  */
 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method);
 
+
 /*
  * This method reset Policy Engine context to default state and update
  * it's state to @param state.
  *
- * @param context is the policy engine context.
- * @param state set Policy engine state to this.
+ * @param context  Policy engine context.
+ * @param state    Set Policy engine state to this.
+ *
+ * @return         none
  */
 void SetPolicyEngineState(PEContext_t *context, const PEState_t state);
 
index 34a7822..b48c674 100644 (file)
@@ -21,8 +21,6 @@
 #ifndef IOTVT_SRM_PSI_H
 #define IOTVT_SRM_PSI_H
 
-#include "cJSON.h"
-
 /**
  * Reads the Secure Virtual Database from PS into dynamically allocated
  * memory buffer.
@@ -30,7 +28,7 @@
  * @note Caller of this method MUST use OCFree() method to release memory
  *       referenced by return value.
  *
- * @return char * reference to memory buffer containing SVR database.
+ * @retval  reference to memory buffer containing SVR database.
  */
 char * GetSVRDatabase();
 
@@ -41,34 +39,8 @@ char * GetSVRDatabase();
  * @param rsrcName string denoting the SVR name ("acl", "cred", "pstat" etc).
  * @param jsonObj JSON object containing the SVR contents.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult UpdateSVRDatabase(const char* rsrcName, cJSON* jsonObj);
 
-/**
- * Reads the Secure Virtual Database from PS
- *
- * @note Caller of this method MUST use OCFree() method to release memory
- *       referenced by return value.
- *
- * @param rsrcName is the name of the field for which file content are read.
-                   if the value is NULL it will send the content of the whole file.
- * @param data is the pointer to the file contents read from the database.
- * @param size is the size to the file contents read.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value
- */
-OCStackResult GetSecureVirtualDatabaseFromPS(const char *rsrcName, uint8_t **data, size_t *size);
-
-/**
- * This method converts updates the persistent storage.
- *
- * @param rsrcName is the name of the secure resource that will be updated.
- * @param cborPayload is the pointer holding cbor payload.
- * @param cborPayload is the size of the cbor payload.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value
- */
-OCStackResult UpdateSecureResourceInPS(const char* rsrcName, uint8_t* cborPayload, size_t size);
-
 #endif //IOTVT_SRM_PSI_H
index facab4e..3134788 100644 (file)
@@ -28,45 +28,36 @@ extern "C" {
 /**
  * Initialize Pstat resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitPstatResource();
 
 /**
  * Perform cleanup for Pstat resources.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult DeInitPstatResource();
 
 /**
- * This method converts PSTAT into the cbor payload.
+ * This method converts JSON PSTAT into binary PSTAT.
  *
- * @param pstat pointer to the initialized pstat structure.
- * @param cborPayload pointer to pstat cbor payload.
- * @param size of the cbor payload converted. It is 0 in case of error,
- * else a positive value if succcessful.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @param[in] jsonStr  pstat data in json string.
+ * @return pointer to OicSecPstat_t.
  */
- OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **cborPayload,
-                                  size_t *cborSize);
+OicSecPstat_t * JSONToPstatBin(const char * jsonStr);
 
 /**
- * This method converts cbor into PSTAT data.
+ * This method converts pstat data into JSON format.
  *
- * @param cborPayload is the pstat data in cbor format.
- * @param size of the cborPayload. In case 0 is provided it assigns CBOR_SIZE (255) value.
- * @param pstat pointer to @ref OicSecPstat_t.
-  *
-  * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @param[in] pstat  pstat data in binary format.
+ * @return pointer to pstat json string.
  */
- OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t cborSize,
-                                  OicSecPstat_t **pstat);
+char * BinToPstatJSON(const OicSecPstat_t * pstat);
 
 /** This function deallocates the memory for OicSecPstat_t.
  *
- * @param pstat is the pointer to @ref OicSecPstat_t.
+ * @param[in] pstat  Pointer to OicSecPstat_t.
  */
 void DeletePstatBinData(OicSecPstat_t* pstat);
 
@@ -81,3 +72,5 @@ void RestorePstatToInitState();
 #endif
 
 #endif //IOTVT_SRM_PSTATR_H
+
+
index 6f8cc8c..3e946f5 100644 (file)
 /**
  * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitSecureResources();
 
 /**
  * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult DestroySecureResources();
 
@@ -44,24 +44,13 @@ OCStackResult DestroySecureResources();
  *
  * @param ehRequest pointer to entity handler request data structure.
  * @param ehRet result code from entity handler.
- * @param rspPayload response payload.
+ * @param rspPayload response payload in JSON.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
         OCEntityHandlerResult ehRet, const char *rspPayload);
 
-/**
- * This method is used by all secure resource modules to send responses to REST queries.
- *
- * @param ehRequest pointer to entity handler request data structure.
- * @param ehRet result code from entity handler.
- * @param cborPayload response payload.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
- */
-OCStackResult SendSRMCBORResponse(const OCEntityHandlerRequest *ehRequest,
-        OCEntityHandlerResult ehRet, uint8_t *cborPayload);
-
 #endif //IOTVT_SRM_RM_H
 
+
index 51f6a3f..eb2643b 100644 (file)
@@ -28,85 +28,85 @@ extern "C" {
 #endif
 
 /**
- * Register Persistent storage callback.
- *
- * @param  persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
- *
- * @return ::OC_STACK_OK  is no errors and successful. ::OC_STACK_INVALID_PARAM for invalid parameter.
+ * @brief   Register Persistent storage callback.
+ * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
+ * @return
+ *     OC_STACK_OK    - No errors; Success
+ *     OC_STACK_INVALID_PARAM - Invalid parameter
  */
 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
 
 /**
- * Get Persistent storage handler pointer.
- *
- * @return The pointer to Persistent Storage callback handler.
+ * @brief   Get Persistent storage handler pointer.
+ * @return
+ *     The pointer to Persistent Storage callback handler
  */
 OCPersistentStorage* SRMGetPersistentStorageHandler();
 
 /**
- * Register request and response callbacks. Requests and responses are delivered in these callbacks.
- *
- * @param reqHandler Request handler callback ( for GET,PUT ..etc)
- * @param respHandler Response handler callback.
- * @param errHandler Error handler callback.
- *
- * @return ::OC_STACK_OK  is no errors and successful. ::OC_STACK_INVALID_PARAM for invalid parameter.
+ * @brief   Register request and response callbacks.
+ *          Requests and responses are delivered in these callbacks.
+ * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
+ * @param   respHandler  [IN] Response handler callback.
+ * @param   errHandler   [IN] Error handler callback.
+ * @return
+ *     OC_STACK_OK    - No errors; Success
+ *     OC_STACK_INVALID_PARAM - Invalid parameter
  */
 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
                                  CAResponseCallback respHandler,
                                  CAErrorCallback errHandler);
 
 /**
- * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @return  ::OC_STACK_OK for Success, otherwise some error value.
+ * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @return  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult SRMInitSecureResources();
 
 /**
- * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @return  none
  */
 void SRMDeInitSecureResources();
 
 /**
- * Initialize Policy Engine context.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @brief   Initialize Policy Engine context.
+ * @return  OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult SRMInitPolicyEngine();
 
 /**
- * Cleanup Policy Engine context.
+ * @brief   Cleanup Policy Engine context.
+ * @return  none
  */
 void SRMDeInitPolicyEngine();
 
 /**
- * Provisioning API response callback.
- *
- * @param object endpoint instance.
- * @param responseInfo instance of CAResponseInfo_t structure.
- *
+ * @brief   Provisioning API response callback.
+ * @param object[IN]       endpoint instance.
+ * @param responseInfo[IN] instance of CAResponseInfo_t structure.
  * @return true if received response is for provisioning API false otherwise.
  */
 typedef bool (*SPResponseCallback) (const CAEndpoint_t *object,
                                     const CAResponseInfo_t *responseInfo);
 
 /**
- * Function to register provisoning API's response callback.
- *
+ * @brief function to register provisoning API's response callback.
  * @param respHandler response handler callback.
  */
 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler);
 
 /**
- * Check the security resource URI.
- * @param uri Pointers to security resource URI.
- * @return true if the URI is one of security resources, otherwise false.
+ * @brief   Check the security resource URI.
+ * @param   uri [IN] Pointers to security resource URI.
+ * @return  true if the URI is one of security resources, otherwise false.
  */
 bool SRMIsSecurityResourceURI(const char* uri);
 
 /**
- * Sends Response
- * @param resposeVal Response @ref SRMAccessResponse_t value.
+ * @brief   Sends Response
+ * @param   resposeVal       SRMAccessResponse_t value
+ * @return  NONE
  */
 void SRMSendResponse(SRMAccessResponse_t responseVal);
 
diff --git a/resource/csdk/security/include/internal/security_internals.h b/resource/csdk/security/include/internal/security_internals.h
deleted file mode 100644 (file)
index e477a0a..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-#ifndef IOTVT_SRM_SECURITY_INTERNALS_H
-#define IOTVT_SRM_SECURITY_INTERNALS_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-OicSecAcl_t* CBORPayloadToAcl(const uint8_t *payload, const size_t size);
-
-void DeleteACLList(OicSecAcl_t* acl);
-
-/**
- * This internal method is to retrieve the default ACL.
- * If SVR database in persistent storage got corrupted or
- * is not available for some reason, a default ACL is created
- * which allows user to initiate ACL provisioning again.
- */
-OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl);
-
-/**
- * This internal method is the entity handler for ACL resources and
- * will handle REST request (GET/PUT/POST/DEL) for them.
- */
-OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag,
-            OCEntityHandlerRequest * ehRequest, void* callbackParameter);
-
-OCStackResult SetDefaultACL(OicSecAcl_t *acl);
-
-/**
- * Converts CBOR payload to SVC.
- *
- * @param cborPayload is the svc payload cbor value that neds to be converted.
- * @param cborSize of the cborPayload. In case size is not known, it is 0.
- * @param svc is the value that is initialized. It is NULL in case of error.
- *
- * @return ::OC_STACK_OK in case successful. ::OC_STACK_INVALID_PARAM if one of
- * the passed parameter is NULL. ::OC_STACK_ERROR in case of error.
- */
-OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size, OicSecSvc_t **svc);
-
-/**
- * Deletes the passed initialized reference to @ref OicSecSvc_t.
- *
- * @param svc is the reference to be deleted.
- */
-void DeleteSVCList(OicSecSvc_t* svc);
-
-/**
- * Create PSTAT resource after default PSTAT initialization is done.
- */
-OCStackResult CreatePstatResource();
-
-/**
- * This internal method is the entity handler for PSTAT resources and
- * will handle REST request (GET/PUT/POST/DEL) for them.
- */
-OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
-                                         OCEntityHandlerRequest * ehRequest);
-
-/**
- * Converts CBOR payload to AMACL.
- *
- * @param cborPayload is the amacl payload cbor value that neds to be converted.
- * @param cborSize of the cborPayload. In case size is not known, it is 0.
- * It should be NON-NULL.
- * @param amacl is the value that is initialized. It is NULL in case of error.
- */
-OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t cborSize,
-                                 OicSecAmacl_t **amacl);
-
-/**
- * This internal method is the entity handler for Cred resources
- * to handle REST request (PUT/POST/DEL)
- */
-OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest,
-                                        void* callbackParameter);
-
-/**
- * This internal method is used to create '/oic/sec/Cred' resource.
- */
-OCStackResult CreateCredResource();
-
-/**
- * This function converts from CBOR format into credential structure .
- * Caller needs to invoke 'free' for allocated structure.
- *
- * @param cborPayload is the CBOR value that is assigned to the structure.
- * @param size is the size of the CBOR.
- * @param secCred is the pointer to instance of @ref OicSecCred_t structure that will be allocated.
- * If it fails it will return NULL.
- *
- * @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
- */
-OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
-                                OicSecCred_t **secCred);
-
-/**
- * This internal method is used to create '/oic/sec/doxm' resource.
- */
-OCStackResult CreateDoxmResource();
-
-/**
- * This internal method is the entity handler for DOXM resources.
- */
-OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest,
-                                        void* callbackParam);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif //IOTVT_SRM_SECURITY_INTERNALS_H
index a7a2df1..568bfa4 100644 (file)
@@ -24,7 +24,6 @@
 #include "securevirtualresourcetypes.h"
 
 extern const char * SVR_DB_FILE_NAME;
-extern const char * SVR_DB_DAT_FILE_NAME;
 extern const char * OIC_MI_DEF;
 
 //AMACL
@@ -113,7 +112,6 @@ extern const char * OIC_JSON_SPM_NAME;
 extern const char * OIC_JSON_PDEVICE_ID_NAME;
 
 extern OicUuid_t WILDCARD_SUBJECT_ID;
-extern OicUuid_t WILDCARD_SUBJECT_B64_ID;
 extern size_t WILDCARD_SUBJECT_ID_LEN;
 extern const char * WILDCARD_RESOURCE_URI;
 
index ce759f8..9db42c5 100644 (file)
@@ -28,33 +28,31 @@ extern "C" {
 /**
  * Initialize SVC resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitSVCResource();
 
 /**
  * Perform cleanup for SVC resources.
+ *
+ * @retval  none
  */
 void DeInitSVCResource();
 
 /**
- * This function converts SVC data into CBOR format.
- * Caller needs to invoke 'free' when done using returned string.
- *
- * @param svc is the instance of @ref OicSecSvc_t structure. In case of NULL it
- * will return ::OC_STACK_INVALID_PARAM.
- * @param cborPayload is the converted cbor value of SVC structure.
- * @param cborSize is the size of the cbor payload. This value is the size of the
- * cborPayload. It should not be NON-NULL value.
+ * This function converts SVC data into JSON format.
+ * Caller needs to invoke 'free' when done using
+ * returned string.
+ * @param svc  instance of OicSecSvc_t structure.
  *
- * @return ::OC_STACK_OK for Success. ::OC_STACK_INVALID in case of invalid parameters.
- * ::OC_STACK_ERROR in case of error in converting to cbor.
+ * @retval  pointer to SVC in json format.
  */
- OCStackResult SVCToCBORPayload(const OicSecSvc_t *svc, uint8_t **cborPayload,
-                                size_t *cborSize);
+char* BinToSvcJSON(const OicSecSvc_t * svc);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_SVCR_H
+
+
index 2957db8..ff2e3e5 100644 (file)
@@ -1,22 +1,22 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/*****************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * 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.
+ *
+ * *****************************************************************/
 
 #ifndef _PBKDF2_H
 #define _PBKDF2_H
@@ -39,14 +39,14 @@ extern "C"
  * Function to derive cryptographic key from the password. (RFC 2898)
  * In this implementation, HMAC with SHA2 is considered as a pseudorandom function
  *
- * @param passwd is the master password from which a derived key is generated.
- * @param pLen is the byte size of the passwd.
- * @param salt is a cryptographic salt.
- * @param saltlen is the byte size of the salt.
- * @param iteration is the number of iterations desired.
- * @param keyLen is the desired byte size of the derived key. (should be the same as
+ * @param[in] passwd is the master password from which a derived key is generated.
+ * @param[in] pLen is the byte size of the passwd.
+ * @param[in] salt is a cryptographic salt.
+ * @param[in] saltlen is the byte size of the salt.
+ * @param[in] iteration is the number of iterations desired.
+ * @param[in] keyLen is the desired byte size of the derived key. (should be the same as
  *       derivedKey size)
- * @param derivedKey is the generated derived key
+ * @param[out] derivedKey is the generated derived key
  *
  * @return  0 on success
  */
index 67f07ac..de15015 100644 (file)
@@ -1,22 +1,22 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/*****************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * 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.
+ *
+ * *****************************************************************/
 
 #ifndef PIN_CALLBACK_DEF_H_
 #define PIN_CALLBACK_DEF_H_
 #define OXM_RANDOM_PIN_SIZE 8
 
 /**
- * Function pointer to print pin code.
+ * Function pointer to print pin code
  */
 typedef void (*GeneratePinCallback)(char* pinData, size_t pinSize);
 
 /**
- * Function pointer to input pin code.
+ * Function pointer to input pin code
  */
 typedef void (*InputPinCallback)(char* pinBuf, size_t bufSize);
 
 /**
- * Function to setting generate PIN callback from user.
+ * Function to setting generate PIN callback from user
  *
- * @param pinCB implementation of generate PIN callback.
+ * @param[in] pinCB implementation of generate PIN callback
  */
 void SetGeneratePinCB(GeneratePinCallback pinCB);
 
 /**
- * Function to setting input PIN callback from user.
+ * Function to setting input PIN callback from user
  *
- * @param pinCB implementation of input PIN callback.
+ * @param[in] pinCB implementation of input PIN callback
  */
 void SetInputPinCB(InputPinCallback pinCB);
 
@@ -58,20 +58,18 @@ void SetInputPinCB(InputPinCallback pinCB);
  * Function to generate random PIN.
  * This function will send generated PIN to user via callback.
  *
- * @param pinBuffer is the reference to the buffer to store the generated PIN data.
- * @param bufferSize is the size of buffer.
- *
- * @return ::OC_STACK_SUCCESS in case of success or other value in case of error.
+ * @param[in,out] pinBuffer   Buffer to store the generated PIN data.
+ * @param[in] bufferSize   Size of buffer
+ * @return OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult GeneratePin(char* pinBuffer, size_t bufferSize);
 
 /**
- * Function to input PIN callback via input callback.
- *
- * @param[in,out] pinBuffer is the reference to the buffer to store the inputed PIN data.
- * @param[in] bufferSize is the size of buffer.
+ * Function to input PIN callback via input callback
  *
- * @return ::OC_STACK_SUCCESS in case of success or other value in ccase of error.
+ * @param[in,out] pinBuffer Buffer to store the inputed PIN data.
+ * @param[in] bufferSize Size of buffer
+ * @return OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult InputPin(char* pinBuffer, size_t bufferSize);
 
index 2357604..d8f7048 100644 (file)
@@ -52,8 +52,8 @@ extern "C" {
 #endif
 
 /**
- * Values used to create bit-maskable enums for single-value response with
- * embedded code.
+ * @brief   Values used to create bit-maskable enums for single-value
+ *          response with embedded code.
  */
 #define ACCESS_GRANTED_DEF            (1 << 0)
 #define ACCESS_DENIED_DEF             (1 << 1)
@@ -189,8 +189,8 @@ typedef enum OSCTBitmask
 } OSCTBitmask_t;
 
 /**
- * /oic/sec/credtype (Credential Type) data type.
- * Derived from OIC Security Spec /oic/sec/cred; see Spec for details.
+ * @brief   /oic/sec/credtype (Credential Type) data type.
+ *          Derived from OIC Security Spec /oic/sec/cred; see Spec for details.
  *              0:  no security mode
  *              1:  symmetric pair-wise key
  *              2:  symmetric group key
@@ -265,7 +265,7 @@ typedef struct OicSecCrl OicSecCrl_t;
 #endif /* __WITH_X509__ */
 
 /**
- * /oic/uuid (Universal Unique Identifier) data type.
+ * @brief   /oic/uuid (Universal Unique Identifier) data type.
  */
 #define UUID_LENGTH 128/8 // 128-bit GUID length
 //TODO: Confirm the length and type of ROLEID.
@@ -281,19 +281,18 @@ struct OicUuid
 };
 
 /**
- * /oic/sec/jwk (JSON Web Key) data type.
- * See JSON Web Key (JWK)  draft-ietf-jose-json-web-key-41
+ * @brief   /oic/sec/jwk (JSON Web Key) data type.
+ *          See JSON Web Key (JWK)  draft-ietf-jose-json-web-key-41
  */
 #define JWK_LENGTH 256/8 // 256 bit key length
 struct OicSecJwk
 {
-    uint8_t                *data;
-    size_t                  len;
+    char                *data;
 };
 
 /**
- * /oic/sec/acl (Access Control List) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/acl (Access Control List) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecAcl
 {
@@ -317,8 +316,9 @@ struct OicSecAcl
 };
 
 /**
- * /oic/sec/amacl (Access Manager Service Accesss Control List) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/amacl (Access Manager Service Accesss Control List)
+ *          data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecAmacl
 {
@@ -337,8 +337,8 @@ struct OicSecAmacl
 };
 
 /**
- * /oic/sec/cred (Credential) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/cred (Credential) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecCred
 {
@@ -363,8 +363,8 @@ struct OicSecCred
 };
 
 /**
- * /oic/sec/doxm (Device Owner Transfer Methods) data type
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/doxm (Device Owner Transfer Methods) data type
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecDoxm
 {
@@ -389,7 +389,7 @@ struct OicSecDoxm
 };
 
 /**
- * /oic/sec/pstat (Provisioning Status) data type.
+ * @brief   /oic/sec/pstat (Provisioning Status) data type.
  * NOTE: this struct is ahead of Spec v0.95 in definition to include Sm.
  * TODO: change comment when reconciled to Spec v0.96.
  */
@@ -409,8 +409,8 @@ struct OicSecPstat
 };
 
 /**
- * /oic/sec/role (Role) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/role (Role) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecRole
 {
@@ -420,8 +420,8 @@ struct OicSecRole
 };
 
 /**
- * /oic/sec/sacl (Signed Access Control List) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/sacl (Signed Access Control List) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecSacl
 {
@@ -430,8 +430,8 @@ struct OicSecSacl
 };
 
 /**
- * /oic/sec/svc (Service requiring a secure connection) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/svc (Service requiring a secure connection) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecSvc
 {
index 029a41b..80548f0 100644 (file)
@@ -33,76 +33,86 @@ extern "C"
 }
 #endif
 
+
 #ifdef __cplusplus
 extern "C" {
 #endif // __cplusplus
 
+
 typedef struct OicParseQueryIter OicParseQueryIter_t;
 
 /**
- * OicRestQueryIter data structure is used for book-keeping
- * sub-REST query's attribute's and value's, starting location &
- * length between calls to GetNextQuery(). This struct needs
- * to be first initialized with ParseQueryIterInit().
+ * @brief   OicRestQueryIter data structure is used for book-keeping
+ *          sub-REST query's attribute's and value's, starting location &
+ *          length between calls to GetNextQuery(). This struct needs
+ *          to be first initialized with ParseQueryIterInit().
  *
  */
 struct OicParseQueryIter
 {
-    unsigned char * attrPos;    /**< stating location of attribute. */
-    size_t attrLen;             /**< length of the attribute. */
-    unsigned char * valPos;     /**< starting location of value. */
-    size_t valLen;              /**< length of the value. */
-    coap_parse_iterator_t pi;   /**< coap struct for tokenizing the query.*/
+    unsigned char * attrPos;    /**<stating location of attribute */
+    size_t attrLen;             /**<length of the attribute */
+    unsigned char * valPos;     /**<starting location of value*/
+    size_t valLen;              /**<length of the value*/
+    coap_parse_iterator_t pi;   /**<coap struct for tokenizing the query*/
 };
 
 /**
- * Macro to verify success of operation.
+ * @def VERIFY_SUCCESS
+ * @brief Macro to verify success of operation.
  * eg: VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), ERROR);
  * @note Invoking function must define "exit:" label for goto functionality to work correctly.
+ *
  */
 #define VERIFY_SUCCESS(tag, op, logLevel) do{ if (!(op)) \
             {OIC_LOG((logLevel), tag, #op " failed!!"); goto exit; } }while(0)
 
 /**
- * Macro to verify argument is not equal to NULL.
+ * @def VERIFY_NON_NULL
+ * @brief Macro to verify argument is not equal to NULL.
  * eg: VERIFY_NON_NULL(TAG, ptrData, ERROR);
  * @note Invoking function must define "exit:" label for goto functionality to work correctly.
+ *
  */
 #define VERIFY_NON_NULL(tag, arg, logLevel) do{ if (NULL == (arg)) \
             { OIC_LOG((logLevel), tag, #arg " is NULL"); goto exit; } }while(0)
 
 /**
- * This method initializes the @ref OicParseQueryIter_t struct.
+ * This method initializes the OicParseQueryIter_t struct
+ *
+ *@param query     - REST query, to be parsed
+ *@param parseIter - OicParseQueryIter_t struct, to be initialized
  *
- * @param query is the REST query, to be parsed.
- * @param parseIter is the @ref OicParseQueryIter_t struct, to be initialized based on the query.
  */
-void ParseQueryIterInit(const unsigned char * query, OicParseQueryIter_t * parseIter);
+void ParseQueryIterInit(unsigned char * query, OicParseQueryIter_t * parseIter);
+
 
 /**
- * This method fills the @ref OicParseQueryIter_t struct with next REST query's
- * attribute's and value's information.
+ * This method fills the OicParseQueryIter_t struct with next REST query's
+ * attribute's and value's information
  *
- * @param parseIter is the @ref OicParseQueryIter_t struct, has next query's attribute's
- *  & value's info.
+ *@param parseIter - OicParseQueryIter_t struct, has next query's attribute's & value's info
  *
- * @return reference to the @ref OicParseQueryIter_t if it has parsed query info, else
- * NULL if it has no query to parse.
+ * @retval
+ *     OicParseQueryIter_t *  - has parsed query info
+ *     NULL                   - has no query to parse
  */
 OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter);
 
+
+
 /**
- * This method acts as a helper function for JSON unmarshalling by various SVR's.
+ * This method acts as a helper funtion for JSON unmarshalling by various SVR's.
  *
- * @param jsonRoot point to the root JSON node containing the OicUuid array.
- * @param arrayItem is the name of the JSON OicUuid array item.
- * @param numUuids is the pointer to the number of OicUuid's available in JSON array.
- * @param uuids is the pointer to the array of OicUuid's.
+ * @param jsonRoot  - root JSON node containing the OicUuid array
+ * @param arrayItem - name of the JSON OicUuid array item
+ * @param numUuids  - pointer to the number of OicUuid's available in JSON array
+ * @param uuids     - pointer to the array of OicUuid's
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
-                           size_t *numUuids, OicUuid_t** uuids);
+OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
+                           size_t *numUuids, OicUuid_t** uuids );
 
 /**
  * Function to getting string of ownership transfer method
index 2385e84..5558dd0 100644 (file)
@@ -116,6 +116,6 @@ provisioning_env.UserInstallTargetLib(provisioningserver, 'libocpmapi')
 if env.get('DTLS_WITH_X509') == '1':
        SConscript('ck_manager/SConscript')
 
-if target_os in ['linux', 'tizen']:
+if target_os in ['linux']:
        SConscript('sample/SConscript')
 
index 57ce4f6..bf7deed 100644 (file)
@@ -75,8 +75,7 @@ typedef OCStackResult (*OTMCreateSecureSession)(OTMContext_t* otmCtx);
 /*\r
  * Callback for creating CoAP payload.\r
  */\r
-typedef OCStackResult (*OTMCreatePayloadCallback)(OTMContext_t* otmCtx, uint8_t **payload, \r
-                                                  size_t *size);\r
+typedef char* (*OTMCreatePayloadCallback)(OTMContext_t* otmCtx);\r
 \r
 /**\r
  * Required callback for performing ownership transfer\r
index 0b9f81e..190b55d 100644 (file)
@@ -1,22 +1,22 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/*****************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * 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.
+ *
+ * *****************************************************************/
 
 #ifndef OXM_JUST_WORKS_H_
 #define OXM_JUST_WORKS_H_
@@ -35,45 +35,35 @@ extern "C" {
 
 /**
  * In case of just works OxM, no need to implement.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM);
 
 /**
  * To establish a secure channel with anonymous cipher suite
  *
- * @param otmCtx Context of OTM, It includes current device information.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx);
 
 /**
  * Generate payload for select OxM request.
  *
- * @param otmCtx Context of OTM, It includes current device information.
- * @param cborPayload is the DOXM CBOR payload including the selected OxM.
- * @note Returned memory should be deallocated by caller.
- * @param cborSize is the size of the cborPayload.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return DOXM JSON payload including the selected OxM.
+ *         NOTE : Returned memory should be deallocated by caller.
  */
-OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
-                                             size_t *cborSize);
+char* CreateJustWorksSelectOxmPayload(OTMContext_t* otmCtx);
 
 /**
  * Generate payload for owner transfer request.
  *
- * @param otmCtx Context of OTM, It includes current device information.
- * @param cborPayload is the DOXM CBOR payload including the owner information.
- * @note Returned memory should be deallocated by caller.
- * @param cborSize is the size of the cborPayload.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return DOXM JSON payload including the owner information.
+ *         NOTE : Returned memory should be deallocated by caller.
  */
-OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
-                                                  size_t *cborSize);
+char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx);
+
 #ifdef __cplusplus
 }
 #endif
index ae7b110..b458ef3 100644 (file)
@@ -1,22 +1,22 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/*****************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * 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.
+ *
+ * *****************************************************************/
 
 #ifndef OXM_RANDOM_PIN_H_
 #define OXM_RANDOM_PIN_H_
@@ -34,46 +34,36 @@ extern "C" {
 /**
  * Callback implementation to input the PIN code from user.
  *
- * @param otmCtx Context of OTM, It includes current device information.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @otmCtx  Context of OTM, It includes current device infomation.
+ * @return OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx);
+OCStackResult InputPinCodeCallback(OTMContext_totmCtx);
 
 /**
- * Callback implemenration to establish a secure channel with PSK cipher suite.
- *
- * @param otmCtx Context of OTM, It includes current device information.
+ * Callback implemenration to establish a secure channel with PSK cipher suite
  *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t *otmCtx);
 
 /**
  * Generate payload for select OxM request.
  *
- * @param otmCtx Context of OTM, It includes current device information.
- * @param cborPaylaod is the DOXM CBOR payload including the selected OxM.
- * @note Returned memory should be deallocated by caller.
- * @param cborSize is the size of the cborPayload.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return DOXM JSON payload including the selected OxM.
+ *         NOTE : Returned memory should be deallocated by caller.
  */
-OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
-                                             size_t *cborSize);
+char* CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx);
 
 /**
  * Generate payload for owner transfer request.
  *
- * @param otmCtx Context of OTM, It includes current device information.
- * @param cborPaylaod is the DOXM CBOR payload including the owner information.
- * @note Returned memory should be deallocated by caller.
- * @param cborSize is the size of the cborPayload.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return DOXM JSON payload including the owner information.
+ *         NOTE : Returned memory should be deallocated by caller.
  */
-OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
-                                                 size_t *cborSize);
+char* CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx);
 
 #ifdef __cplusplus
 }
index 74e4568..46fe3d8 100644 (file)
@@ -23,6 +23,8 @@ Import('env')
 
 provisioning_env = env.Clone()
 
+target_os = env.get('TARGET_OS')
+
 ######################################################################
 # Build flags
 ######################################################################
@@ -60,20 +62,18 @@ if env.get('DTLS_WITH_X509') == '1':
        provisioning_env.AppendUnique(LIBS = ['asn1'])
 provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
 
-provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
 ######################################################################
 # Source files and Targets
 ######################################################################
 
-provisioningclient = provisioning_env.Program('provisioningclient', 'provisioningclient.c')
-sampleserver_justworks = provisioning_env.Program('sampleserver_justworks', 'sampleserver_justworks.cpp')
-sampleserver_randompin = provisioning_env.Program('sampleserver_randompin', 'sampleserver_randompin.cpp')
-
 src_dir = provisioning_env.get('SRC_DIR')
 sec_provisioning_src_dir = src_dir + '/resource/csdk/security/provisioning/sample/'
 sec_provisioning_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/sample/'
 
+provisioningclient = provisioning_env.Program('provisioningclient', 'provisioningclient.c')
+sampleserver_justworks = provisioning_env.Program('sampleserver_justworks', 'sampleserver_justworks.cpp')
+sampleserver_randompin = provisioning_env.Program('sampleserver_randompin', 'sampleserver_randompin.cpp')
+
 clientjson = provisioning_env.Install(sec_provisioning_build_dir,
                                         sec_provisioning_src_dir + 'oic_svr_db_client.json')
 justworksjson = provisioning_env.Install(sec_provisioning_build_dir,
index eb16fd6..df7754b 100644 (file)
  * *****************************************************************/
 #include <string.h>
 #include "credentialgenerator.h"
-#include "base64.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "ocpayload.h"
-#include "payload_logging.h"
+#include "logger.h"
 #include "credresource.h"
 #include "ocrandom.h"
-#include "srmutility.h"
+#include "base64.h"
 #include "stdbool.h"
 #include "securevirtualresourcetypes.h"
 #ifdef __WITH_X509__
 
 #define TAG "SRPAPI-CG"
 
-static const char OIC_JSON_CRV_NAME[] = "crv";
-static const char OIC_JSON_KTY_NAME[] = "kty";
-static const char OIC_JSON_CERTIFICATE_NAME[] = "x5c";
-static const char OIC_JSON_D_NAME[] = "d";
-static const char kty[] = "EC";
-static const char crv[] = "P-256";
-static const uint8_t CertMapSize = 3;
+/**
+ * @def PM_VERIFY_SUCCESS
+ * @brief Macro to verify success of operation.
+ *        eg: PM_VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), OC_STACK_ERROR, ERROR);
+ * @note Invoking function must define "bail:" label for goto functionality to work correctly and
+ *       must define "OCStackResult res" for setting error code.
+ * */
+#define PM_VERIFY_SUCCESS(tag, op, errCode, logLevel) { if (!(op)) \
+                       {OIC_LOG((logLevel), tag, #op " failed!!"); res = errCode; goto bail;} }
+/**
+ * @def PM_VERIFY_NON_NULL
+ * @brief Macro to verify argument is not equal to NULL.
+ *        eg: PM_VERIFY_NON_NULL(TAG, ptrData, ERROR);
+ * @note Invoking function must define "bail:" label for goto functionality to work correctly.
+ * */
+#define PM_VERIFY_NON_NULL(tag, arg, errCode, logLevel) { if (NULL == (arg)) \
+                   { OIC_LOG((logLevel), tag, #arg " is NULL"); res = errCode; goto bail;} }
 
 OCStackResult PMGeneratePairWiseCredentials(OicSecCredType_t type, size_t keySize,
-        const OicUuid_t *ptDeviceId, const OicUuid_t *firstDeviceId,
-        const OicUuid_t *secondDeviceId, OicSecCred_t **firstCred, OicSecCred_t **secondCred)
+                                    const OicUuid_t *ptDeviceId,
+                                    const OicUuid_t *firstDeviceId, const OicUuid_t *secondDeviceId,
+                                    OicSecCred_t **firstCred, OicSecCred_t **secondCred)
 {
+
     if (NULL == ptDeviceId || NULL == firstDeviceId || NULL != *firstCred || \
         NULL == secondDeviceId || NULL != *secondCred)
     {
@@ -61,30 +71,42 @@ OCStackResult PMGeneratePairWiseCredentials(OicSecCredType_t type, size_t keySiz
         return OC_STACK_INVALID_PARAM;
     }
     OCStackResult res = OC_STACK_ERROR;
+    uint8_t* privData = NULL;
+    char* base64Buff = NULL;
     OicSecCred_t *tempFirstCred = NULL;
     OicSecCred_t *tempSecondCred = NULL;
 
     size_t privDataKeySize = keySize;
 
-    uint8_t *privData = (uint8_t *)OICCalloc(privDataKeySize, sizeof(uint8_t));
-    VERIFY_NON_NULL(TAG, privData, ERROR);
+    privData = (uint8_t*) OICCalloc(privDataKeySize,sizeof(uint8_t));
+    PM_VERIFY_NON_NULL(TAG, privData, OC_STACK_NO_MEMORY, ERROR);
 
-    OCFillRandomMem(privData, privDataKeySize);
+    OCFillRandomMem(privData,privDataKeySize);
+
+    uint32_t outLen = 0;
+
+    base64Buff = (char*) OICCalloc(B64ENCODE_OUT_SAFESIZE(privDataKeySize) + 1, sizeof(char));
+    PM_VERIFY_NON_NULL(TAG, base64Buff, OC_STACK_NO_MEMORY, ERROR);
+    int memReq = (B64ENCODE_OUT_SAFESIZE(privDataKeySize) + 1) * sizeof(char);
+    B64Result b64Ret = b64Encode(privData, privDataKeySize*sizeof(uint8_t), base64Buff,
+                                 memReq, &outLen);
+    PM_VERIFY_SUCCESS(TAG, B64_OK == b64Ret, OC_STACK_ERROR, ERROR);
 
     // TODO: currently owner array is 1. only provisioning tool's id.
-    tempFirstCred =  GenerateCredential(secondDeviceId, type, NULL, privData, 1, ptDeviceId);
-    VERIFY_NON_NULL(TAG, tempFirstCred, ERROR);
+    tempFirstCred =  GenerateCredential(secondDeviceId, type, NULL, base64Buff, 1, ptDeviceId);
+    PM_VERIFY_NON_NULL(TAG, tempFirstCred, OC_STACK_ERROR, ERROR);
 
     // TODO: currently owner array is 1. only provisioning tool's id.
-    tempSecondCred =  GenerateCredential(firstDeviceId, type, NULL, privData, 1, ptDeviceId);
-    VERIFY_NON_NULL(TAG, tempSecondCred, ERROR);
+    tempSecondCred =  GenerateCredential(firstDeviceId, type, NULL, base64Buff, 1, ptDeviceId);
+    PM_VERIFY_NON_NULL(TAG, tempSecondCred, OC_STACK_ERROR, ERROR);
 
     *firstCred = tempFirstCred;
     *secondCred = tempSecondCred;
     res = OC_STACK_OK;
 
-exit:
+bail:
     OICFree(privData);
+    OICFree(base64Buff);
 
     if(res != OC_STACK_OK)
     {
@@ -101,22 +123,17 @@ exit:
 /**
  * Function to compose JSON Web Key (JWK) string from a certificate and a public key.
  *
- * @param certificateChain    Array of Base64 encoded certificate strings.
- * @param chainLength         Number of the certificates in certificateChain.
- * @param payload Valid JWK CBOR on success, or NULL on fail.
-
+ * @param[in]  certificateChain    Array of Base64 encoded certificate strings.
+ * @param[in]  chainLength         Number of the certificates in certificateChain.
+ * @return     Valid JWK string on success, or NULL on fail.
  */
-static OCStackResult CreateCertificatePublicJWK(const char *const *certificateChain,
-       const size_t chainLength, uint8_t **cborPayload, size_t *size)
+static char *CreateCertificatePublicJWK(const char *const *certificateChain,
+                                        const size_t chainLength)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    *cborPayload = NULL;
-    *size = 0;
-
     if (NULL == certificateChain || chainLength == 0)
     {
         OIC_LOG(ERROR, TAG, "Error CreateCertificatePublicJWK: Invalid params");
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     size_t certChainSize = 0;
@@ -129,118 +146,70 @@ static OCStackResult CreateCertificatePublicJWK(const char *const *certificateCh
         else
         {
             OIC_LOG(ERROR, TAG, "Error CreateCertificatePublicJWK: Invalid params");
-            return OC_STACK_INVALID_PARAM;
+            return NULL;
         }
-    }
 
-    // cborArbitraryLen is a value to conver field names and cbor map, cbor array.
-    size_t cborArbitraryLen = 255;
-    size_t cborLen = certChainSize + cborArbitraryLen;
-    int64_t cborEncoderResult = CborNoError;
-    CborEncoder encoder = { .end = 0 };
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
-
-    CborEncoder credMap = { .end = 0 };
-    cborEncoderResult |= cbor_encoder_create_map(&encoder, &credMap, CertMapSize);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map.");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_KTY_NAME,
-            strlen(OIC_JSON_KTY_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-    cborEncoderResult |= cbor_encode_text_string(&credMap, kty, strlen(kty));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_CRV_NAME,
-            strlen(OIC_JSON_CRV_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-    cborEncoderResult |= cbor_encode_text_string(&credMap, crv, strlen(crv));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_CERTIFICATE_NAME,
-            strlen(OIC_JSON_CERTIFICATE_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Certificate Name.");
-    CborEncoder certs = { {.ptr = NULL }, .end = 0 };
-    cborEncoderResult |= cbor_encoder_create_array(&credMap, &certs, chainLength);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Certificate Array.");
-    for (size_t i = 0; i < chainLength; i++)
+    }
+    /* certificates in the json array taken in quotes and separated by a comma
+     * so we have to count the number of characters (number of commas and quotes) required
+     * for embedding certificates in the array depending on the number of certificates in chain
+     * each certificate except last embeded in  "\"%s\"," */
+    const int numCommasAndQuotes = chainLength * 3 - 1;
+    const char firstPart[] = "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x5c\":[";
+    const char secondPart[] = "]}";
+    /* to calculate the size of JWK public part we need to add the value of first and  second parts,
+     * size of certificate chain, number of additional commas and quotes and 1 for string termination symbol */
+    size_t certPubJWKLen = strlen(firstPart) + strlen(secondPart)
+                                             + certChainSize + numCommasAndQuotes + 1;
+    char *certPubJWK = (char *)OICMalloc(certPubJWKLen);
+
+    if (NULL != certPubJWK)
     {
-        cborEncoderResult |= cbor_encode_byte_string(&certs, (uint8_t *)certificateChain[i], strlen(certificateChain[i]));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Certificate Chain.");
+        OICStrcpy(certPubJWK, certPubJWKLen, firstPart);
+        size_t offset = strlen(firstPart);
+        for (size_t i = 0; i < chainLength; ++i)
+        {
+            offset += snprintf(certPubJWK + offset, certPubJWKLen - offset, "\"%s\",", certificateChain[i]);
+        }
+        snprintf(certPubJWK + offset - 1, certPubJWK - offset - 1, secondPart);
     }
-    cborEncoderResult |= cbor_encoder_close_container(&credMap, &certs);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Certificate Chain.");
-
-    cborEncoderResult |= cbor_encoder_close_container(&encoder, &credMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
-
-    *cborPayload = outPayload;
-    *size = encoder.ptr - outPayload;
-    ret = OC_STACK_OK;
-
-exit:
-    return ret;
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+    }
+    return certPubJWK;
 }
 
 /**
  * Function to compose JWK string from a private key.
  *
- * @param privateKey to be converted to CBOR.
- * @ Valid JWK string on success, or NULL on fail.
+ * @param[in]  privateKey    Base64 encoded private key.
+ * @return     Valid JWK string on success, or NULL on fail.
  */
-OCStackResult CreateCertificatePrivateJWK(const char *privateKey, uint8_t **cborPayload,
-        size_t *size)
+static char *CreateCertificatePrivateJWK(const char *privateKey)
 {
-    *cborPayload = NULL;
-    *size = 0;
-    OCStackResult ret = OC_STACK_INVALID_PARAM;
-    VERIFY_NON_NULL(TAG, privateKey, ERROR);
-
-    // cborArbitraryLen is a value to conver field names and cbor map, cbor array.
-    size_t cborArbitraryLen = 255;
-    size_t cborLen = strlen(privateKey) + cborArbitraryLen;
-    int64_t cborEncoderResult = CborNoError;
-    ret = OC_STACK_ERROR;
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-
-    CborEncoder encoder = { .end = 0 };
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
-
-    CborEncoder credMap = { .end = 0 };
-    cborEncoderResult |= cbor_encoder_create_map(&encoder, &credMap, 3);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_KTY_NAME,
-            strlen(OIC_JSON_KTY_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-    cborEncoderResult |= cbor_encode_text_string(&credMap, kty, strlen(kty));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_CRV_NAME,
-            strlen(OIC_JSON_CRV_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-    cborEncoderResult |= cbor_encode_text_string(&credMap, crv, strlen(crv));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_D_NAME,
-            strlen(OIC_JSON_D_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding D tag.");
-    cborEncoderResult |= cbor_encode_byte_string(&credMap, (uint8_t *)privateKey, strlen(privateKey));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding D Value.");
-
-    cborEncoderResult |= cbor_encoder_close_container(&encoder, &credMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
-
-    *cborPayload = outPayload;
-    *size = encoder.ptr - outPayload;
-    ret = OC_STACK_OK;
-
-exit:
-    return ret;
+    if (NULL == privateKey)
+    {
+        OIC_LOG(ERROR, TAG, "Error privateKey is NULL");
+        return NULL;
+    }
+    const char firstPart[] = "{\"kty\":\"EC\",\"crv\":\"P-256\",\"d\":\"";
+    const char secondPart[] = "\"}";
+    size_t len = strlen(firstPart) + strlen(secondPart) + strlen(privateKey) + 1;
+    char *certPrivJWK = (char *)OICMalloc(len);
+
+    if (NULL != certPrivJWK)
+    {
+        snprintf(certPrivJWK, len, "%s%s%s", firstPart, privateKey, secondPart);
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+    }
+    return certPrivJWK;
 }
 
+
 /**
  * Function to generate Base64 encoded credential data for device.
  *
@@ -370,6 +339,7 @@ memclean:
     return OC_STACK_OK;
 }
 
+
 OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
         const OicUuid_t *deviceId, OicSecCred_t **const cred)
 {
@@ -387,18 +357,8 @@ OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
         return OC_STACK_ERROR;
     }
 
-    uint8_t *publicJWK = NULL;
-    size_t len = 0;
-    if (OC_STACK_OK == CreateCertificatePublicJWK(certificateChain, certChainLen, &publicJWK, &len))
-    {
-
-    }
-    uint8_t *privateJWK = NULL;
-    size_t len1 = 0;
-    if (OC_STACK_OK == CreateCertificatePrivateJWK(privKey, &privateJWK, &len1))
-    {
-
-    }
+    char *publicJWK = CreateCertificatePublicJWK(certificateChain, certChainLen);
+    char *privateJWK = CreateCertificatePrivateJWK(privKey);
     for (size_t i = 0; i < certChainLen; ++i)
     {
         OICFree(certificateChain[i]);
index 185dd7d..486cf73 100644 (file)
@@ -58,8 +58,6 @@
 #include "srmutility.h"
 #include "provisioningdatabasemanager.h"
 #include "oxmrandompin.h"
-#include "ocpayload.h"
-#include "payload_logging.h"
 
 #define TAG "OTM"
 
@@ -439,10 +437,16 @@ static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
         OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
         //Generating new credential for provisioning tool
         size_t ownLen = 1;
+        uint32_t outLen = 0;
+
+        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(ownerPSK)) + 1] = {};
+        B64Result b64Ret = b64Encode(ownerPSK, sizeof(ownerPSK), base64Buff, sizeof(base64Buff),
+                &outLen);
+        VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
 
         OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
                 SYMMETRIC_PAIR_WISE_KEY, NULL,
-                ownerPSK, ownLen, &ptDeviceID);
+                base64Buff, ownLen, &ptDeviceID);
         VERIFY_NON_NULL(TAG, cred, ERROR);
 
         res = AddCredential(cred);
@@ -539,14 +543,12 @@ static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
-        uint8_t size = 0;
-        OicSecPstat_t* pstat = NULL;
-        OCStackResult result = CBORPayloadToPstat(
-                ((OCSecurityPayload*)clientResponse->payload)->securityData1,
-                size, &pstat);
-        if(NULL == pstat && result != OC_STACK_OK)
+
+        OicSecPstat_t* pstat = JSONToPstatBin(
+                ((OCSecurityPayload*)clientResponse->payload)->securityData);
+        if(NULL == pstat)
         {
-            OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
+            OIC_LOG(ERROR, TAG, "Error while converting json to pstat bin");
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
@@ -930,8 +932,8 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
         newCredential.privateData.data = NULL;
 
         //Send owner credential to new device : PUT /oic/sec/cred [ owner credential ]
-        size_t size = 0;
-        if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData1, &size))
+        secPayload->securityData = BinToCredJSON(&newCredential);
+        if (NULL == secPayload->securityData)
         {
             OICFree(secPayload);
             OIC_LOG(ERROR, TAG, "Error while converting bin to json");
@@ -992,14 +994,11 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
-                                                                         &secPayload->securityData1,
-                                                                         &size);
-    if (OC_STACK_OK != res && NULL == secPayload->securityData1)
-    {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
+    secPayload->securityData = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx);
+    if (NULL == secPayload->securityData)
+    {
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting bin to json");
         return OC_STACK_ERROR;
     }
 
@@ -1007,9 +1006,9 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
     cbData.cb = &OwnerTransferModeHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    res = OCDoResource(NULL, OC_REST_PUT, query,
-                       &deviceInfo->endpoint, (OCPayload *)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query,
+                                     &deviceInfo->endpoint, (OCPayload*)secPayload,
+                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1088,24 +1087,23 @@ static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res =  g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
-            otmCtx, &secPayload->securityData1, &size);
-    if (NULL == secPayload->securityData1)
+    secPayload->securityData =
+        g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(otmCtx);
+    if (NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
         return OC_STACK_INVALID_PARAM;
     }
-    OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData1);
+    OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData);
 
     OCCallbackData cbData;
     cbData.cb = &OwnerUuidUpdateHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
 
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
-            deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1147,14 +1145,10 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
     }
 
     otmCtx->selectedDeviceInfo->doxm->owned = true;
-
-    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
-            &secPayload->securityData1, &size);
-    if (OC_STACK_OK != res && NULL == secPayload->securityData1)
+    secPayload->securityData = BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    if (NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
         return OC_STACK_INVALID_PARAM;
     }
@@ -1165,8 +1159,8 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
 
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1205,13 +1199,11 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData1,
-                                           &size);
-   if (OC_STACK_OK != res)
+    secPayload->securityData = BinToPstatJSON(deviceInfo->pstat);
+    if (NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting pstat bin to json");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -1219,8 +1211,8 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
     cbData.cb = &OperationModeUpdateHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1375,6 +1367,7 @@ error:
     OICFree(otmCtx->ctxResultArray);
     OICFree(otmCtx);
     return res;
+
 }
 
 OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
@@ -1403,15 +1396,14 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
-            &secPayload->securityData1, &size))
+    secPayload->securityData = BinToPstatJSON(otmCtx->selectedDeviceInfo->pstat);
+    if (NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload);
         SetResult(otmCtx, OC_STACK_INVALID_JSON);
         return OC_STACK_INVALID_JSON;
     }
-    OIC_LOG_V(INFO, TAG, "Created payload for commit hash: %s",secPayload->securityData1);
+    OIC_LOG_V(INFO, TAG, "Created payload for commit hash: %s",secPayload->securityData);
 
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
@@ -1442,3 +1434,4 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
 
     return ret;
 }
+
index 480a50d..ca65bdd 100644 (file)
 
 #define TAG "OXM_JustWorks"
 
-OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **payload, size_t *size)
+char* CreateJustWorksSelectOxmPayload(OTMContext_t* otmCtx)
 {
-    if (!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_JUST_WORKS;
-    *payload = NULL;
-    *size = 0;
-
-    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
+    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
 }
 
-OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
+char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx)
 {
-    if (!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     OicUuid_t uuidPT = {.id={0}};
@@ -58,14 +55,11 @@ OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t
     if (OC_STACK_OK != GetDoxmDeviceID(&uuidPT))
     {
         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return OC_STACK_ERROR;
+        return NULL;
     }
     memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH);
 
-    *payload = NULL;
-    *size = 0;
-
-    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);;
+    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
 }
 
 OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM)
@@ -78,7 +72,7 @@ OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM)
 OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx)
 {
     OIC_LOG(INFO, TAG, "IN CreateSecureSessionJustWorksCallback");
-    if (!otmCtx || !otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -108,13 +102,13 @@ OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx)
     }
     OIC_LOG(INFO, TAG, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
 
-    OCProvisionDev_t *selDevInfo = otmCtx->selectedDeviceInfo;
+    OCProvisionDev_tselDevInfo = otmCtx->selectedDeviceInfo;
     CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
     if(NULL == endpoint)
     {
         return OC_STACK_NO_MEMORY;
     }
-    memcpy(endpoint, &selDevInfo->endpoint, sizeof(CAEndpoint_t));
+    memcpy(endpoint,&selDevInfo->endpoint,sizeof(CAEndpoint_t));
     endpoint->port = selDevInfo->securePort;
 
     caresult = CAInitiateHandshake(endpoint);
index 04643c5..138c274 100644 (file)
 
 #define TAG "OXM_RandomPIN"
 
-OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
+char* CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx)
 {
-    *payload = NULL;
-    *size = 0;
-    if(!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_RANDOM_DEVICE_PIN;
 
-    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
+    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
 }
 
-OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
+char* CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     OicUuid_t uuidPT = {.id={0}};
-    *payload = NULL;
-    *size = 0;
 
     if (OC_STACK_OK != GetDoxmDeviceID(&uuidPT))
     {
         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return OC_STACK_ERROR;
+        return NULL;
     }
     memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH);
 
-    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
+    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
 }
 
-OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx)
+OCStackResult InputPinCodeCallback(OTMContext_totmCtx)
 {
-    if (!otmCtx || !otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -83,7 +79,7 @@ OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx)
     uint8_t pinData[OXM_RANDOM_PIN_SIZE + 1];
 
     OCStackResult res = InputPin((char*)pinData, OXM_RANDOM_PIN_SIZE + 1);
-    if (OC_STACK_OK != res)
+    if(OC_STACK_OK != res)
     {
         OIC_LOG(ERROR, TAG, "Failed to input PIN");
         return res;
@@ -110,7 +106,7 @@ OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx)
 {
     OIC_LOG(INFO, TAG, "IN CreateSecureSessionRandomPinCallbak");
 
-    if (!otmCtx || !otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -131,9 +127,10 @@ OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx)
     }
     OIC_LOG(INFO, TAG, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
 
+
     OCProvisionDev_t* selDevInfo = otmCtx->selectedDeviceInfo;
     CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
-    if (NULL == endpoint)
+    if(NULL == endpoint)
     {
         return OC_STACK_NO_MEMORY;
     }
@@ -151,3 +148,4 @@ OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx)
 
     return OC_STACK_OK;
 }
+
index 31208db..2e4158b 100644 (file)
@@ -489,17 +489,16 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                 OIC_LOG(INFO, TAG, "Unknown payload type");
                 return OC_STACK_KEEP_TRANSACTION;
             }
-            OicSecDoxm_t *ptrDoxm = NULL;
-            uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData1;
-            OCStackResult res = CBORPayloadToDoxm(payload, 0, &ptrDoxm);
-            if ((NULL == ptrDoxm) && (OC_STACK_OK != res))
+            OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
+                            ((OCSecurityPayload*)clientResponse->payload)->securityData);
+            if (NULL == ptrDoxm)
             {
-                OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
+                OIC_LOG(INFO, TAG, "Ignoring malformed JSON");
                 return OC_STACK_KEEP_TRANSACTION;
             }
             else
             {
-                OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
+                OIC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
 
                 //If this is owend device discovery we have to filter out the responses.
                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
index 35bcd77..d3056c0 100644 (file)
@@ -40,7 +40,6 @@
 #include "provisioningdatabasemanager.h"
 #include "base64.h"
 #include "utlist.h"
-#include "ocpayload.h"
 
 #ifdef __WITH_X509__
 #include "crlresource.h"
@@ -298,21 +297,21 @@ static OCStackResult provisionCredentials(const OicSecCred_t *cred,
         OCClientResponseHandler responseHandler)
 {
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-    if (!secPayload)
+    if(!secPayload)
     {
         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData1, &size);
-    if((OC_STACK_OK != res) && (NULL == secPayload->securityData1))
+    secPayload->securityData = BinToCredJSON(cred);
+    if(NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
         return OC_STACK_NO_MEMORY;
     }
 
+    OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         deviceInfo->endpoint.addr,
@@ -498,7 +497,7 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     crlData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
     if (crlData->resArr == NULL)
     {
-        OICFree(secPayload->securityData1);
+        OICFree(secPayload->securityData);
         OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
@@ -542,16 +541,16 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData1, &size);
+    secPayload->securityData = BinToCredJSON(cred);
 
-    if ((OC_STACK_OK != res) || (NULL == secPayload->securityData1))
+    if (NULL == secPayload->securityData)
     {
         OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
+        OIC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
         return OC_STACK_NO_MEMORY;
     }
 
+    OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         deviceInfo->endpoint.addr,
@@ -560,7 +559,8 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
                         query, sizeof(query), OIC_RSRC_CRED_URI))
     {
         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload->securityData);
+        OICFree(secPayload);
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -848,13 +848,15 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    if(OC_STACK_OK != AclToCBORPayload(acl, &secPayload->securityData1, &size))
+    secPayload->securityData = BinToAclJSON(acl);
+    if(NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to BinToAclJSON");
         return OC_STACK_NO_MEMORY;
     }
+    OIC_LOG_V(INFO, TAG, "ACL : %s", secPayload->securityData);
+
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         selectedDeviceInfo->endpoint.addr,
@@ -872,7 +874,8 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
     if (aclData == NULL)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload->securityData);
+        OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
@@ -886,7 +889,8 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     if (aclData->resArr == NULL)
     {
         OICFree(aclData);
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload->securityData);
+        OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
index aa5e752..4e85e79 100644 (file)
@@ -28,64 +28,73 @@ using namespace std;
 
 TEST(JustWorksOxMTest, NullParam)
 {
+
     OTMContext_t* otmCtx = NULL;
-    uint8_t *payloadRes = NULL;
-    size_t size = 0;
+    OCStackResult res = OC_STACK_ERROR;
+    char* payloadRes;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
-    EXPECT_EQ(OC_STACK_OK, LoadSecretJustWorksCallback(otmCtx));
+    res = LoadSecretJustWorksCallback(otmCtx);
+    EXPECT_TRUE(OC_STACK_OK == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateSecureSessionJustWorksCallback(otmCtx));
+    res = CreateSecureSessionJustWorksCallback(otmCtx);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateJustWorksSelectOxmPayload(otmCtx, &payloadRes, &size));
+    payloadRes = CreateJustWorksSelectOxmPayload(otmCtx);
     EXPECT_TRUE(NULL == payloadRes);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateJustWorksOwnerTransferPayload(otmCtx, &payloadRes, &size));
+    payloadRes = CreateJustWorksOwnerTransferPayload(otmCtx);
     EXPECT_TRUE(NULL == payloadRes);
 
     OTMContext_t otmCtx2;
     otmCtx2.selectedDeviceInfo = NULL;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
-    EXPECT_EQ(OC_STACK_OK, LoadSecretJustWorksCallback(&otmCtx2));
+    res = LoadSecretJustWorksCallback(&otmCtx2);
+    EXPECT_TRUE(OC_STACK_OK == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateSecureSessionJustWorksCallback(&otmCtx2));
+    res = CreateSecureSessionJustWorksCallback(&otmCtx2);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateJustWorksSelectOxmPayload(&otmCtx2, &payloadRes, &size));
+    payloadRes = CreateJustWorksSelectOxmPayload(&otmCtx2);
     EXPECT_TRUE(NULL == payloadRes);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateJustWorksOwnerTransferPayload(&otmCtx2, &payloadRes, &size));
+    payloadRes = CreateJustWorksOwnerTransferPayload(&otmCtx2);
     EXPECT_TRUE(NULL == payloadRes);
 }
 
 TEST(RandomPinOxMTest, NullParam)
 {
     OTMContext_t* otmCtx = NULL;
-    uint8_t *payloadRes = NULL;
-    size_t size = 0;
+    OCStackResult res = OC_STACK_ERROR;
+    char* payloadRes;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InputPinCodeCallback(otmCtx));
+    res = InputPinCodeCallback(otmCtx);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateSecureSessionRandomPinCallback(otmCtx));
+    res = CreateSecureSessionRandomPinCallback(otmCtx);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePinBasedSelectOxmPayload(otmCtx, &payloadRes, &size));
+    payloadRes = CreatePinBasedSelectOxmPayload(otmCtx);
     EXPECT_TRUE(NULL == payloadRes);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePinBasedOwnerTransferPayload(otmCtx, &payloadRes, &size));
+    payloadRes = CreatePinBasedOwnerTransferPayload(otmCtx);
     EXPECT_TRUE(NULL == payloadRes);
 
     OTMContext_t otmCtx2;
     otmCtx2.selectedDeviceInfo = NULL;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InputPinCodeCallback(&otmCtx2));
+    res = InputPinCodeCallback(&otmCtx2);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateSecureSessionRandomPinCallback(&otmCtx2));
+    res = CreateSecureSessionRandomPinCallback(&otmCtx2);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePinBasedSelectOxmPayload(&otmCtx2, &payloadRes, &size));
+    payloadRes = CreatePinBasedSelectOxmPayload(&otmCtx2);
     EXPECT_TRUE(NULL == payloadRes);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePinBasedOwnerTransferPayload(&otmCtx2, &payloadRes, &size));
+    payloadRes = CreatePinBasedOwnerTransferPayload(&otmCtx2);
     EXPECT_TRUE(NULL == payloadRes);
 }
index 6f46f43..e142ca7 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
-#include <strings.h>
-#endif
 #include <stdlib.h>
-
+#include <string.h>
 #include "ocstack.h"
-#include "ocserverrequest.h"
+#include "logger.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "ocrandom.h"
-#include "ocpayload.h"
+#include "cJSON.h"
+#include "base64.h"
+#include "resourcemanager.h"
+#include "aclresource.h"
+#include "psinterface.h"
 #include "utlist.h"
-#include "payload_logging.h"
 #include "srmresourcestrings.h"
-#include "aclresource.h"
 #include "doxmresource.h"
-#include "resourcemanager.h"
 #include "srmutility.h"
-#include "psinterface.h"
-
-#include "security_internals.h"
+#include "ocserverrequest.h"
+#include <stdlib.h>
+#ifdef WITH_ARDUINO
+#include <string.h>
+#else
+#include <strings.h>
+#endif
 
 #define TAG  "SRM-ACL"
 #define NUMBER_OF_SEC_PROV_RSCS 4
 #define NUMBER_OF_DEFAULT_SEC_RSCS 2
 
-// CborSize is the default cbor payload size being used.
-static uint64_t CborSize = 255;
-
-static OicSecAcl_t *gAcl = NULL;
-static OCResourceHandle gAclHandle = NULL;
+OicSecAcl_t               *gAcl = NULL;
+static OCResourceHandle    gAclHandle = NULL;
 
 /**
  * This function frees OicSecAcl_t object's fields and object itself.
@@ -58,9 +54,9 @@ static OCResourceHandle gAclHandle = NULL;
 static void FreeACE(OicSecAcl_t *ace)
 {
     size_t i;
-    if (NULL == ace)
+    if(NULL == ace)
     {
-        OIC_LOG(ERROR, TAG, "Invalid Parameter");
+        OIC_LOG (ERROR, TAG, "Invalid Parameter");
         return;
     }
 
@@ -72,9 +68,9 @@ static void FreeACE(OicSecAcl_t *ace)
     OICFree(ace->resources);
 
     //Clean Period
-    if (ace->periods)
+    if(ace->periods)
     {
-        for (i = 0; i < ace->prdRecrLen; i++)
+        for(i = 0; i < ace->prdRecrLen; i++)
         {
             OICFree(ace->periods[i]);
         }
@@ -82,9 +78,9 @@ static void FreeACE(OicSecAcl_t *ace)
     }
 
     //Clean Recurrence
-    if (ace->recurrences)
+    if(ace->recurrences)
     {
-        for (i = 0; i < ace->prdRecrLen; i++)
+        for(i = 0; i < ace->prdRecrLen; i++)
         {
             OICFree(ace->recurrences[i]);
         }
@@ -112,376 +108,298 @@ void DeleteACLList(OicSecAcl_t* acl)
     }
 }
 
-static size_t OicSecAclSize(const OicSecAcl_t *secAcl)
+/*
+ * This internal method converts ACL data into JSON format.
+ *
+ * Note: Caller needs to invoke 'free' when finished done using
+ * return string.
+ */
+char * BinToAclJSON(const OicSecAcl_t * acl)
 {
-    if (!secAcl)
-    {
-        return 0;
-    }
-    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
-    size_t size = 0;
-    while (acl)
-    {
-       size++;
-       acl = acl->next;
-    }
-    return size;
-}
+    cJSON *jsonRoot = NULL;
+    char *jsonStr = NULL;
 
-OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, size_t *size)
-{
-    OCStackResult ret = OC_STACK_INVALID_PARAM;
-    int64_t cborEncoderResult = CborNoError;
-    uint8_t *outPayload = NULL;
-    size_t cborLen = *size;
-    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
-    VERIFY_NON_NULL(TAG, secAcl, ERROR);
-
-    CborEncoder encoder;
-    CborEncoder oicSecAclArray;
-    if (cborLen == 0)
+    if (acl)
     {
-        cborLen = CborSize;
-    }
-    *size = 0;
-    *payload = NULL;
-
-    // Please note: This has been initialized prior to use because of VERIFY macro
+        jsonRoot = cJSON_CreateObject();
+        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+        cJSON *jsonAclArray = NULL;
+        cJSON_AddItemToObject (jsonRoot, OIC_JSON_ACL_NAME, jsonAclArray = cJSON_CreateArray());
+        VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
 
-    // Create ACL Array
-    cborEncoderResult |= cbor_encoder_create_array(&encoder, &oicSecAclArray, OicSecAclSize(secAcl));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACL Array.");
-
-    while (acl)
-    {
-        CborEncoder oicSecAclMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-        // ACL Map size - Number of mandatory items
-        uint8_t aclMapSize = 4;
-        // Create ACL Map
-        if (acl->periods)
-        {
-            ++aclMapSize;
-        }
-        if (acl->recurrences)
-        {
-            ++aclMapSize;
-        }
-        cborEncoderResult |= cbor_encoder_create_map(&oicSecAclArray, &oicSecAclMap, aclMapSize);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACL Map");
-
-        // Subject -- Mandatory
-        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_SUBJECT_NAME,
-            sizeof(OIC_JSON_SUBJECT_NAME) - 1);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Name Tag.");
-        size_t inLen = 0;
-        if (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0)
+        while(acl)
         {
-            inLen = WILDCARD_SUBJECT_ID_LEN;
-        }
-        else
-        {
-            inLen = sizeof(OicUuid_t);
-        }
-        cborEncoderResult |= cbor_encode_byte_string(&oicSecAclMap, (uint8_t *)acl->subject.id, inLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
-
-        // Resources
-        CborEncoder resources = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RESOURCES_NAME,
-            sizeof(OIC_JSON_RESOURCES_NAME) -1);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Tag.");
-        cborEncoderResult |= cbor_encoder_create_array(&oicSecAclMap, &resources, acl->resourcesLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array.");
-        for (size_t i = 0; i < acl->resourcesLen; i++)
-        {
-            cborEncoderResult |= cbor_encode_text_string(&resources, acl->resources[i],
-                strlen(acl->resources[i]));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array Value.");
+            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+            uint32_t outLen = 0;
+            size_t inLen = 0;
+            B64Result b64Ret = B64_OK;
 
-        }
-        cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &resources);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name Array.");
-
-        // Permissions -- Mandatory
-        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERMISSION_NAME,
-            sizeof(OIC_JSON_PERMISSION_NAME) -1);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Tag.");
-        cborEncoderResult |= cbor_encode_int(&oicSecAclMap, acl->permission);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Value.");
-
-        // Period -- Not Mandatory
-        if (acl->periods)
-        {
-            CborEncoder period = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-            cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERIODS_NAME,
-                sizeof(OIC_JSON_PERIODS_NAME) -1);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Tag.");
-            cborEncoderResult |= cbor_encoder_create_array(&oicSecAclMap, &period, acl->prdRecrLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Array.");
-            for (size_t i = 0; i < acl->prdRecrLen; i++)
-            {
-                cborEncoderResult |= cbor_encode_text_string(&period, acl->periods[i],
-                    strlen(acl->periods[i]));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value in Array.");
+            cJSON *jsonAcl = cJSON_CreateObject();
 
+            // Subject -- Mandatory
+            outLen = 0;
+            if (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0)
+            {
+                inLen = WILDCARD_SUBJECT_ID_LEN;
+            }
+            else
+            {
+                inLen =  sizeof(OicUuid_t);
+            }
+            b64Ret = b64Encode(acl->subject.id, inLen, base64Buff,
+                sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+            cJSON_AddStringToObject(jsonAcl, OIC_JSON_SUBJECT_NAME, base64Buff );
+
+            // Resources -- Mandatory
+            cJSON *jsonRsrcArray = NULL;
+            cJSON_AddItemToObject (jsonAcl, OIC_JSON_RESOURCES_NAME, jsonRsrcArray = cJSON_CreateArray());
+            VERIFY_NON_NULL(TAG, jsonRsrcArray, ERROR);
+            for (size_t i = 0; i < acl->resourcesLen; i++)
+            {
+                cJSON_AddItemToArray (jsonRsrcArray, cJSON_CreateString(acl->resources[i]));
             }
-            cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &period);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Period Array.");
-        }
 
-        // Recurrence -- Not Mandatory
-        if (acl->recurrences)
-        {
-            CborEncoder recurrences = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-            cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RECURRENCES_NAME,
-                sizeof(OIC_JSON_RECURRENCES_NAME) -1);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Tag.");
-            cborEncoderResult |= cbor_encoder_create_array(&oicSecAclMap, &recurrences, acl->prdRecrLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array.");
-            for (size_t i = 0; i < acl->prdRecrLen; i++)
+            // Permissions -- Mandatory
+            cJSON_AddNumberToObject (jsonAcl, OIC_JSON_PERMISSION_NAME, acl->permission);
+
+            //Period & Recurrence -- Not Mandatory
+            if(0 != acl->prdRecrLen)
             {
-                cborEncoderResult |= cbor_encode_text_string(&recurrences, acl->recurrences[i],
-                    strlen(acl->recurrences[i]));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
+                cJSON *jsonPeriodArray = NULL;
+                cJSON_AddItemToObject (jsonAcl, OIC_JSON_PERIODS_NAME,
+                        jsonPeriodArray = cJSON_CreateArray());
+                VERIFY_NON_NULL(TAG, jsonPeriodArray, ERROR);
+                for (size_t i = 0; i < acl->prdRecrLen; i++)
+                {
+                    cJSON_AddItemToArray (jsonPeriodArray,
+                            cJSON_CreateString(acl->periods[i]));
+                }
             }
-            cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &recurrences);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
-        }
 
-        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_OWNERS_NAME,
-            sizeof(OIC_JSON_OWNERS_NAME) - 1);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Name.");
-        CborEncoder owners = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-        cborEncoderResult |= cbor_encoder_create_array(&oicSecAclMap, &owners, acl->ownersLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Array.");
-        for (size_t i = 0; i < acl->ownersLen; i++)
-        {
-            cborEncoderResult = cbor_encode_byte_string(&owners, (uint8_t *)acl->owners[i].id,
-                sizeof(acl->owners[i].id));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Array Value.");
+            //Recurrence -- Not Mandatory
+            if(0 != acl->prdRecrLen && acl->recurrences)
+            {
+                cJSON *jsonRecurArray  = NULL;
+                cJSON_AddItemToObject (jsonAcl, OIC_JSON_RECURRENCES_NAME,
+                        jsonRecurArray = cJSON_CreateArray());
+                VERIFY_NON_NULL(TAG, jsonRecurArray, ERROR);
+                for (size_t i = 0; i < acl->prdRecrLen; i++)
+                {
+                    cJSON_AddItemToArray (jsonRecurArray,
+                            cJSON_CreateString(acl->recurrences[i]));
+                }
+            }
 
-        }
-        cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &owners);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Owner Array.");
+            // Owners -- Mandatory
+            cJSON *jsonOwnrArray = NULL;
+            cJSON_AddItemToObject (jsonAcl, OIC_JSON_OWNERS_NAME, jsonOwnrArray = cJSON_CreateArray());
+            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
+            for (size_t i = 0; i < acl->ownersLen; i++)
+            {
+                outLen = 0;
 
-        cborEncoderResult |= cbor_encoder_close_container(&oicSecAclArray, &oicSecAclMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Map.");
+                b64Ret = b64Encode(acl->owners[i].id, sizeof(((OicUuid_t*)0)->id), base64Buff,
+                    sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
 
-        acl = acl->next;
-    }
-    cborEncoderResult |= cbor_encoder_close_container(&encoder, &oicSecAclArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Array.");
+                cJSON_AddItemToArray (jsonOwnrArray, cJSON_CreateString(base64Buff));
+            }
 
-    if (CborNoError == cborEncoderResult)
-    {
-        *size = encoder.ptr - outPayload;
-        *payload = outPayload;
-        ret = OC_STACK_OK;
-    }
-exit:
-    if (CborErrorOutOfMemory == cborEncoderResult)
-    {
-        // reallocate and try again!
-        OICFree(outPayload);
-        // Since the allocated initial memory failed, double the memory.
-        cborLen += encoder.ptr - encoder.end;
-        cborEncoderResult = CborNoError;
-        if (OC_STACK_OK == AclToCBORPayload(secAcl, &outPayload, &cborLen))
-        {
-            *size = cborLen;
-            *payload = outPayload;
-            ret = OC_STACK_OK;
+            // Attach current acl node to Acl Array
+            cJSON_AddItemToArray(jsonAclArray, jsonAcl);
+            acl = acl->next;
         }
+
+        jsonStr = cJSON_PrintUnformatted(jsonRoot);
     }
 
-    if (cborEncoderResult != CborNoError)
+exit:
+    if (jsonRoot)
     {
-        OICFree(outPayload);
-        outPayload = NULL;
-        *size = 0;
-        ret = OC_STACK_ERROR;
+        cJSON_Delete(jsonRoot);
     }
-
-    return ret;
+    return jsonStr;
 }
 
-// This function converts CBOR format to ACL data.
-// Caller needs to invoke 'free' when done using
-// note: This function is used in unit test hence not declared static,
-OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
+/*
+ * This internal method converts JSON ACL into binary ACL.
+ */
+OicSecAcl_t * JSONToAclBin(const char * jsonStr)
 {
-    if (NULL == cborPayload)
-    {
-        return NULL;
-    }
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecAcl_t * headAcl = NULL;
+    OicSecAcl_t * prevAcl = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonAclArray = NULL;
 
-    CborValue aclCbor = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-    CborParser parser = { .end = NULL, .flags = 0 };
-    CborError cborFindResult = CborNoError;
-    cbor_parser_init(cborPayload, size, 0, &parser, &aclCbor);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
-    OicSecAcl_t *headAcl = NULL;
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborValue aclArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-    cborFindResult = cbor_value_enter_container(&aclCbor, &aclArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Array.");
+    jsonAclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
+    VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
 
-    while (cbor_value_is_valid(&aclArray))
+    if (cJSON_Array == jsonAclArray->type)
     {
-        CborValue aclMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-        cborFindResult = cbor_value_enter_container(&aclArray, &aclMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Map.");
-
-        OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-        VERIFY_NON_NULL(TAG, acl, ERROR);
+        int numAcl = cJSON_GetArraySize(jsonAclArray);
+        int idx = 0;
 
-        while (cbor_value_is_valid(&aclMap))
+        VERIFY_SUCCESS(TAG, numAcl > 0, INFO);
+        do
         {
-            char* name = NULL;
-            size_t len = 0;
-            CborType type = cbor_value_get_type(&aclMap);
-            if (type == CborTextStringType)
+            cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
+            VERIFY_NON_NULL(TAG, jsonAcl, ERROR);
+
+            OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+            VERIFY_NON_NULL(TAG, acl, ERROR);
+
+            headAcl = (headAcl) ? headAcl : acl;
+            if (prevAcl)
             {
-                cborFindResult = cbor_value_dup_text_string(&aclMap, &name, &len, NULL);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
-                cborFindResult = cbor_value_advance(&aclMap);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACL Map.");
+                prevAcl->next = acl;
             }
-            if (name)
-            {
-                // Subject -- Mandatory
-                if (strcmp(name, OIC_JSON_SUBJECT_NAME)  == 0)
-                {
-                    uint8_t *subjectId = NULL;
-                    cborFindResult = cbor_value_dup_byte_string(&aclMap, &subjectId, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Subject Name Value.");
-                    memcpy(acl->subject.id, subjectId, len);
-                    OICFree(subjectId);
-                }
 
-                // Resources -- Mandatory
-                if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
+
+            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
+
+            // Subject -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_SUBJECT_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            outLen = 0;
+            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                        sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->subject.id)), ERROR);
+            memcpy(acl->subject.id, base64Buff, outLen);
+
+            // Resources -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RESOURCES_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            acl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, acl->resourcesLen > 0, ERROR);
+            acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
+            VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
+
+            size_t idxx = 0;
+            do
+            {
+                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
+
+                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
+                acl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, (acl->resources[idxx]), ERROR);
+                OICStrcpy(acl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
+            } while ( ++idxx < acl->resourcesLen);
+
+            // Permissions -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl,
+                                OIC_JSON_PERMISSION_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            acl->permission = jsonObj->valueint;
+
+            //Period -- Not Mandatory
+            cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonAcl,
+                    OIC_JSON_PERIODS_NAME);
+            if(jsonPeriodObj)
+            {
+                VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type,
+                               ERROR);
+                acl->prdRecrLen = (size_t)cJSON_GetArraySize(jsonPeriodObj);
+                if(acl->prdRecrLen > 0)
                 {
-                    CborValue resources = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                    cborFindResult = cbor_value_get_array_length(&aclMap, &acl->resourcesLen);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Rec Array Len Value.");
-
-                    cborFindResult = cbor_value_enter_container(&aclMap, &resources);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering a Rec Array.");
+                    acl->periods = (char**)OICCalloc(acl->prdRecrLen,
+                                    sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->periods, ERROR);
 
-                    acl->resources = (char **) OICMalloc(acl->resourcesLen * sizeof(char*));
-                    VERIFY_NON_NULL(TAG, acl->resources, ERROR);
-                    int i = 0;
-                    while (cbor_value_is_text_string(&resources))
+                    cJSON *jsonPeriod = NULL;
+                    for(size_t i = 0; i < acl->prdRecrLen; i++)
                     {
-                        cborFindResult = cbor_value_dup_text_string(&resources, &acl->resources[i++],
-                            &len, NULL);
-                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Rec Array Value.");
-                        cborFindResult = cbor_value_advance(&resources);
-                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Rec Array Advance.");
+                        jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);
+                        VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);
+
+                        jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
+                        acl->periods[i] = (char*)OICMalloc(jsonObjLen);
+                        VERIFY_NON_NULL(TAG, acl->periods[i], ERROR);
+                        OICStrcpy(acl->periods[i], jsonObjLen,
+                                  jsonPeriod->valuestring);
                     }
                 }
+            }
 
-                // Permissions -- Mandatory
-                if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
-                {
-                    cborFindResult = cbor_value_get_uint64(&aclMap, (uint64_t *) &acl->permission);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a PERM Value.");
-                }
-
-                // Period -- Not mandatory
-                if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0)
-                {
-                    CborValue period = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                    cborFindResult = cbor_value_get_array_length(&aclMap, &acl->prdRecrLen);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Len.");
-                    cborFindResult = cbor_value_enter_container(&aclMap, &period);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Map.");
-                    int i = 0;
-                    while (cbor_value_is_text_string(&period))
-                    {
-                        cborFindResult = cbor_value_dup_text_string(&period, &acl->periods[i++],
-                            &len, NULL);
-                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Value.");
-                        cborFindResult = cbor_value_advance(&period);
-                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a Period Array.");
-                    }
-                }
+            //Recurrence -- Not mandatory
+            cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl,
+                                        OIC_JSON_RECURRENCES_NAME);
+            if(jsonRecurObj)
+            {
+                VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type,
+                               ERROR);
 
-                // Recurrence -- Not mandatory
-                if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
+                if(acl->prdRecrLen > 0)
                 {
-                    CborValue recurrences = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                    cborFindResult = cbor_value_enter_container(&aclMap, &recurrences);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array.");
-                    int i = 0;
-                    while (cbor_value_is_text_string(&recurrences))
-                    {
-                        cborFindResult = cbor_value_dup_text_string(&recurrences,
-                            &acl->recurrences[i++], &len, NULL);
-                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array Value.");
-                        cborFindResult = cbor_value_advance(&recurrences);
-                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Closing Recurrence Array.");
-                    }
-                }
+                    acl->recurrences = (char**)OICCalloc(acl->prdRecrLen,
+                                             sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
 
-                // Owners -- Mandatory
-                if (strcmp(name, OIC_JSON_OWNERS_NAME) == 0)
-                {
-                    CborValue owners = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                    cborFindResult = cbor_value_get_array_length(&aclMap, &acl->ownersLen);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Getting Owner Array Len.");
-                    cborFindResult = cbor_value_enter_container(&aclMap, &owners);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Owner Array.");
-                    int i = 0;
-                    acl->owners = (OicUuid_t *)OICMalloc(acl->ownersLen * sizeof(OicUuid_t));
-                    VERIFY_NON_NULL(TAG, acl->owners, ERROR);
-                    while (cbor_value_is_valid(&owners))
+                    cJSON *jsonRecur = NULL;
+                    for(size_t i = 0; i < acl->prdRecrLen; i++)
                     {
-                        uint8_t *owner = NULL;
-                        cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
-                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Owner Array Value.");
-                        cborFindResult = cbor_value_advance(&owners);
-                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Owners Array.");
-                        memcpy(acl->owners[i].id, owner, len);
-                        OICFree(owner);
+                        jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
+                        VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
+                        jsonObjLen = strlen(jsonRecur->valuestring) + 1;
+                        acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
+                        VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
+                        OICStrcpy(acl->recurrences[i], jsonObjLen,
+                              jsonRecur->valuestring);
                     }
                 }
             }
-            if (type != CborMapType && cbor_value_is_valid(&aclMap))
-            {
-                cborFindResult = cbor_value_advance(&aclMap);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Array.");
-            }
-        }
 
-        acl->next = NULL;
-        if (headAcl == NULL)
-        {
-            headAcl = acl;
-        }
-        else
-        {
-            OicSecAcl_t *temp = headAcl;
-            while (temp->next)
+            // Owners -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_OWNERS_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            acl->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, acl->ownersLen > 0, ERROR);
+            acl->owners = (OicUuid_t*)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
+            VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
+
+            idxx = 0;
+            do
             {
-                temp = temp->next;
-            }
-            temp->next = acl;
-        }
-        if (cbor_value_is_valid(&aclArray))
-        {
-            cborFindResult = cbor_value_advance(&aclArray);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Array.");
-        }
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
+
+                outLen = 0;
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
+                            sizeof(base64Buff), &outLen);
+
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->owners[idxx].id)),
+                                    ERROR);
+                memcpy(acl->owners[idxx].id, base64Buff, outLen);
+            } while ( ++idxx < acl->ownersLen);
+
+            prevAcl = acl;
+        } while( ++idx < numAcl);
     }
 
+    ret = OC_STACK_OK;
+
 exit:
-    if (cborFindResult != CborNoError)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
         DeleteACLList(headAcl);
         headAcl = NULL;
@@ -489,18 +407,37 @@ exit:
     return headAcl;
 }
 
-/**
+static bool UpdatePersistentStorage(const OicSecAcl_t *acl)
+{
+    // Convert ACL data into JSON for update to persistent storage
+    char *jsonStr = BinToAclJSON(acl);
+    if (jsonStr)
+    {
+        cJSON *jsonAcl = cJSON_Parse(jsonStr);
+        OICFree(jsonStr);
+
+        if ((jsonAcl) && (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl)))
+        {
+            return true;
+        }
+        cJSON_Delete(jsonAcl);
+    }
+    return false;
+}
+
+/*
  * This method removes ACE for the subject and resource from the ACL
  *
- * @param subject of the ACE
- * @param resource of the ACE
+ * @param subject  - subject of the ACE
+ * @param resource - resource of the ACE
  *
  * @return
- *     ::OC_STACK_RESOURCE_DELETED on success
- *     ::OC_STACK_NO_RESOURCE on failure to find the appropriate ACE
- *     ::OC_STACK_INVALID_PARAM on invalid parameter
+ *     OC_STACK_RESOURCE_DELETED on success
+ *     OC_STACK_NO_RESOURC on failure to find the appropriate ACE
+ *     OC_STACK_INVALID_PARAM on invalid parameter
  */
-static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
+static OCStackResult RemoveACE(const OicUuid_t * subject,
+                               const char * resource)
 {
     OIC_LOG(DEBUG, TAG, "IN RemoveACE");
 
@@ -509,18 +446,18 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
     bool deleteFlag = false;
     OCStackResult ret = OC_STACK_NO_RESOURCE;
 
-    if (memcmp(subject->id, &WILDCARD_SUBJECT_ID, sizeof(subject->id)) == 0)
+    if(memcmp(subject->id, &WILDCARD_SUBJECT_ID, sizeof(subject->id)) == 0)
     {
-        OIC_LOG_V(ERROR, TAG, "%s received invalid parameter", __func__ );
+        OIC_LOG_V (ERROR, TAG, "%s received invalid parameter", __func__ );
         return  OC_STACK_INVALID_PARAM;
     }
 
     //If resource is NULL then delete all the ACE for the subject.
-    if (NULL == resource || resource[0] == '\0')
+    if(NULL == resource || resource[0] == '\0')
     {
         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
         {
-            if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+            if(memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
             {
                 LL_DELETE(gAcl, acl);
                 FreeACE(acl);
@@ -536,9 +473,9 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
         //the resource array
         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
         {
-            if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+            if(memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
             {
-                if (1 == acl->resourcesLen && strcmp(acl->resources[0], resource) == 0)
+                if(1 == acl->resourcesLen && strcmp(acl->resources[0],  resource) == 0)
                 {
                     LL_DELETE(gAcl, acl);
                     FreeACE(acl);
@@ -547,24 +484,24 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
                 }
                 else
                 {
-                    size_t resPos = -1;
+                    int resPos = -1;
                     size_t i;
-                    for (i = 0; i < acl->resourcesLen; i++)
+                    for(i = 0; i < acl->resourcesLen; i++)
                     {
-                        if (strcmp(acl->resources[i], resource) == 0)
+                        if(strcmp(acl->resources[i],  resource) == 0)
                         {
                             resPos = i;
                             break;
                         }
                     }
-                    if (0 <= (int) resPos)
+                    if((0 <= resPos))
                     {
                         OICFree(acl->resources[resPos]);
                         acl->resources[resPos] = NULL;
                         acl->resourcesLen -= 1;
-                        for (i = resPos; i < acl->resourcesLen; i++)
+                        for(i = (size_t)resPos; i < acl->resourcesLen; i++)
                         {
-                            acl->resources[i] = acl->resources[i + 1];
+                            acl->resources[i] = acl->resources[i+1];
                         }
                         deleteFlag = true;
                         break;
@@ -574,31 +511,17 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
         }
     }
 
-    if (deleteFlag)
+    if(deleteFlag)
     {
-        // In case of unit test do not update persistant storage.
-        if (memcmp(subject->id, &WILDCARD_SUBJECT_B64_ID, sizeof(subject->id)) == 0)
+        if(UpdatePersistentStorage(gAcl))
         {
             ret = OC_STACK_RESOURCE_DELETED;
         }
-        else
-        {
-            uint8_t *payload = NULL;
-            size_t size = 0;
-            if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
-            {
-                if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size))
-                {
-                    ret = OC_STACK_RESOURCE_DELETED;
-                }
-                OICFree(payload);
-            }
-        }
     }
     return ret;
 }
 
-/**
+/*
  * This method parses the query string received for REST requests and
  * retrieves the 'subject' field.
  *
@@ -609,25 +532,33 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
  */
 static bool GetSubjectFromQueryString(const char *query, OicUuid_t *subject)
 {
-    OicParseQueryIter_t parseIter = { .attrPos = NULL };
+    OicParseQueryIter_t parseIter = {.attrPos=NULL};
+
+    ParseQueryIterInit((unsigned char *)query, &parseIter);
 
-    ParseQueryIterInit((unsigned char *) query, &parseIter);
 
-    while (GetNextQuery (&parseIter))
+    while(GetNextQuery(&parseIter))
     {
-        if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_SUBJECT_NAME, parseIter.attrLen) == 0)
+        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME, parseIter.attrLen) == 0)
         {
             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
-            memcpy(subject->id, parseIter.valPos, parseIter.valLen);
+            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
+            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen, base64Buff,
+                    sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (B64_OK == b64Ret && outLen <= sizeof(subject->id)), ERROR);
+            memcpy(subject->id, base64Buff, outLen);
+
             return true;
         }
     }
 
 exit:
-    return false;
+   return false;
 }
 
-/**
+/*
  * This method parses the query string received for REST requests and
  * retrieves the 'resource' field.
  *
@@ -639,17 +570,16 @@ exit:
  */
 static bool GetResourceFromQueryString(const char *query, char *resource, size_t resourceSize)
 {
-    OicParseQueryIter_t parseIter = { .attrPos = NULL };
+    OicParseQueryIter_t parseIter = {.attrPos=NULL};
 
-    ParseQueryIterInit((unsigned char *) query, &parseIter);
+    ParseQueryIterInit((unsigned char *)query, &parseIter);
 
-    while (GetNextQuery (&parseIter))
+    while(GetNextQuery(&parseIter))
     {
-        if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen)
-                == 0)
+        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen) == 0)
         {
             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
-            OICStrcpy(resource, resourceSize, (char *) parseIter.valPos);
+            OICStrcpy(resource, resourceSize, (char *)parseIter.valPos);
 
             return true;
         }
@@ -659,26 +589,28 @@ exit:
    return false;
 }
 
-static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *ehRequest)
+
+
+static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    OIC_LOG(INFO, TAG, "HandleACLGetRequest processing the request");
-    uint8_t* payload = NULL;
-    size_t size = 0;
-    OCEntityHandlerResult ehRet;
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    char* jsonStr = NULL;
 
     // Process the REST querystring parameters
-    if (ehRequest->query)
+    if(ehRequest->query)
     {
-        OIC_LOG(DEBUG, TAG, "HandleACLGetRequest processing query");
+        OIC_LOG (DEBUG, TAG, "HandleACLGetRequest processing query");
 
-        OicUuid_t subject = {.id= { 0 } };
-        char resource[MAX_URI_LENGTH] = { 0 };
+        OicUuid_t subject = {.id={0}};
+        char resource[MAX_URI_LENGTH] = {0};
 
         OicSecAcl_t *savePtr = NULL;
         const OicSecAcl_t *currentAce = NULL;
 
         // 'Subject' field is MUST for processing a querystring in REST request.
-        VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
+        VERIFY_SUCCESS(TAG,
+                       true == GetSubjectFromQueryString(ehRequest->query, &subject),
+                       ERROR);
 
         GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
 
@@ -687,7 +619,7 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
          * Below code needs to be updated for scenarios when Subject have
          * multiple ACE's in ACL resource.
          */
-        while ((currentAce = GetACLResourceData(&subject, &savePtr)))
+        while((currentAce = GetACLResourceData(&subject, &savePtr)))
         {
             /*
              * If REST querystring contains a specific resource, we need
@@ -695,121 +627,104 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
              */
             if (resource[0] != '\0')
             {
-                for (size_t n = 0; n < currentAce->resourcesLen; n++)
+                for(size_t n = 0; n < currentAce->resourcesLen; n++)
                 {
-                    if ((currentAce->resources[n])
-                            && (0 == strcmp(resource, currentAce->resources[n])
-                                    || 0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
+                    if((currentAce->resources[n]) &&
+                            (0 == strcmp(resource, currentAce->resources[n]) ||
+                             0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
                     {
-                        // Convert ACL data into CBOR format for transmission
-                        if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
-                        {
-                            ehRet = OC_EH_ERROR;
-                        }
+                        // Convert ACL data into JSON for transmission
+                        jsonStr = BinToAclJSON(currentAce);
                         goto exit;
                     }
                 }
             }
             else
             {
-                // Convert ACL data into CBOR format for transmission
-                if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
-                {
-                    ehRet = OC_EH_ERROR;
-                }
+                // Convert ACL data into JSON for transmission
+                jsonStr = BinToAclJSON(currentAce);
                 goto exit;
             }
         }
     }
     else
     {
-        // Convert ACL data into CBOR format for transmission.
-        if (OC_STACK_OK != AclToCBORPayload(gAcl, &payload, &size))
-        {
-            ehRet = OC_EH_ERROR;
-        }
+        // Convert ACL data into JSON for transmission
+        jsonStr = BinToAclJSON(gAcl);
     }
+
 exit:
-    // A device should always have a default acl. Therefore, payload should never be NULL.
-    ehRet = (payload ? OC_EH_OK : OC_EH_ERROR);
+    ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
 
     // Send response payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, payload);
+    SendSRMResponse(ehRequest, ehRet, jsonStr);
 
-    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
+    OICFree(jsonStr);
+
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleACLPostRequest(const OCEntityHandlerRequest *ehRequest)
+static OCEntityHandlerResult HandleACLPostRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    OIC_LOG(INFO, TAG, "HandleACLPostRequest processing the request");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    // Convert CBOR into ACL data and update to SVR buffers. This will also validate the ACL data received.
-    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;;
-    if (payload)
+    // Convert JSON ACL data into binary. This will also validate the ACL data received.
+    OicSecAcl_t* newAcl = JSONToAclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if (newAcl)
     {
-        OicSecAcl_t *newAcl = CBORPayloadToAcl(payload, CborSize);
-        if (newAcl)
+        // Append the new ACL to existing ACL
+        LL_APPEND(gAcl, newAcl);
+
+        if(UpdatePersistentStorage(gAcl))
         {
-            // Append the new ACL to existing ACL
-            LL_APPEND(gAcl, newAcl);
-            size_t size = 0;
-            // In case of unit test do not update persistant storage.
-            if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
-                || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
-            {
-                ehRet = OC_EH_RESOURCE_CREATED;
-            }
-            else
-            {
-                uint8_t *cborPayload = NULL;
-                if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size))
-                {
-                    if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK)
-                    {
-                        ehRet = OC_EH_RESOURCE_CREATED;
-                    }
-                }
-            }
+            ehRet = OC_EH_RESOURCE_CREATED;
         }
     }
 
     // Send payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, NULL);
+    SendSRMResponse(ehRequest, ehRet, NULL);
 
-    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
 static OCEntityHandlerResult HandleACLDeleteRequest(const OCEntityHandlerRequest *ehRequest)
 {
-    OIC_LOG(DEBUG, TAG, "Processing ACLDeleteRequest");
+    OIC_LOG (DEBUG, TAG, "Processing ACLDeleteRequest");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    OicUuid_t subject = { .id= { 0 } };
-    char resource[MAX_URI_LENGTH] = { 0 };
+    OicUuid_t subject = {.id={0}};
+    char resource[MAX_URI_LENGTH] = {0};
 
     VERIFY_NON_NULL(TAG, ehRequest->query, ERROR);
 
     // 'Subject' field is MUST for processing a querystring in REST request.
-    VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
+    VERIFY_SUCCESS(TAG,
+            true == GetSubjectFromQueryString(ehRequest->query, &subject),
+            ERROR);
 
     GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
 
-    if (OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
+    if(OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
     {
         ehRet = OC_EH_RESOURCE_DELETED;
     }
 
 exit:
     // Send payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, NULL);
+    SendSRMResponse(ehRequest, ehRet, NULL);
 
     return ehRet;
 }
 
-OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest,
-        void* callbackParameter)
+/*
+ * This internal method is the entity handler for ACL resources and
+ * will handle REST request (GET/PUT/POST/DEL) for them.
+ */
+OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParameter)
 {
     OIC_LOG(DEBUG, TAG, "Received request ACLEntityHandler");
     (void)callbackParameter;
@@ -823,7 +738,7 @@ OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandler
     if (flag & OC_REQUEST_FLAG)
     {
         // TODO :  Handle PUT method
-        OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -840,17 +755,17 @@ OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandler
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMCBORResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL);
         }
     }
 
     return ehRet;
 }
 
-/**
+/*
  * This internal method is used to create '/oic/sec/acl' resource.
  */
-static OCStackResult CreateACLResource()
+OCStackResult CreateACLResource()
 {
     OCStackResult ret;
 
@@ -864,24 +779,23 @@ static OCStackResult CreateACLResource()
 
     if (OC_STACK_OK != ret)
     {
-        OIC_LOG(FATAL, TAG, "Unable to instantiate ACL resource");
+        OIC_LOG (FATAL, TAG, "Unable to instantiate ACL resource");
         DeInitACLResource();
     }
     return ret;
 }
 
-// This function sets the default ACL and is defined for the unit test only.
-OCStackResult SetDefaultACL(OicSecAcl_t *acl)
-{
-    gAcl = acl;
-    return OC_STACK_OK;
-}
-
-OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
+/*
+ * This internal method is to retrieve the default ACL.
+ * If SVR database in persistent storage got corrupted or
+ * is not available for some reason, a default ACL is created
+ * which allows user to initiate ACL provisioning again.
+ */
+OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    OicUuid_t ownerId = { .id = { 0 } };
+    OicUuid_t ownerId = {.id = {0}};
 
     /*
      * TODO In future, when new virtual resources will be added in OIC
@@ -908,22 +822,22 @@ OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
         return OC_STACK_INVALID_PARAM;
     }
 
-    OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t));
     VERIFY_NON_NULL(TAG, acl, ERROR);
 
     // Subject -- Mandatory
     memcpy(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(acl->subject));
 
     // Resources -- Mandatory
-    acl->resourcesLen = sizeof(rsrcs) / sizeof(rsrcs[0]);
+    acl->resourcesLen = sizeof(rsrcs)/sizeof(rsrcs[0]);
 
-    acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
+    acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
     VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
 
-    for (size_t i = 0; i < acl->resourcesLen; i++)
+    for (size_t i = 0; i <  acl->resourcesLen; i++)
     {
         size_t len = strlen(rsrcs[i]) + 1;
-        acl->resources[i] = (char*) OICMalloc(len * sizeof(char));
+        acl->resources[i] = (char*)OICMalloc(len * sizeof(char));
         VERIFY_NON_NULL(TAG, (acl->resources[i]), ERROR);
         OICStrcpy(acl->resources[i], len, rsrcs[i]);
     }
@@ -934,18 +848,11 @@ OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
     acl->recurrences = NULL;
 
     // Device ID is the owner of this default ACL
-    if (GetDoxmResourceData() != NULL)
-    {
-        ret = GetDoxmDeviceID(&ownerId);
-        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
-    }
-    else
-    {
-        OCRandomUuidResult rdm = OCGenerateUuid(ownerId.id);
-        VERIFY_SUCCESS(TAG, RAND_UUID_OK == rdm, FATAL);
-    }
+    ret = GetDoxmDeviceID( &ownerId);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
+
     acl->ownersLen = 1;
-    acl->owners = (OicUuid_t*) OICMalloc(sizeof(OicUuid_t));
+    acl->owners = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
     VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
     memcpy(acl->owners, &ownerId, sizeof(OicUuid_t));
 
@@ -965,29 +872,30 @@ exit:
     return ret;
 }
 
+/**
+ * Initialize ACL resource by loading data from persistent storage.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult InitACLResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    uint8_t *data = NULL;
-    size_t size = 0;
-    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_ACL_NAME, &data, &size);
-    // If database read failed
-    if (ret != OC_STACK_OK)
-    {
-        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
-    if (data)
+    // Read ACL resource from PS
+    char* jsonSVRDatabase = GetSVRDatabase();
+
+    if (jsonSVRDatabase)
     {
-        // Read ACL resource from PS
-        gAcl = CBORPayloadToAcl(data, size);
+        // Convert JSON ACL into binary format
+        gAcl = JSONToAclBin(jsonSVRDatabase);
+        OICFree(jsonSVRDatabase);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default ACL is created
      * which allows user to initiate ACL provisioning again.
      */
-    if (!gAcl)
+    if (!jsonSVRDatabase || !gAcl)
     {
         GetDefaultACL(&gAcl);
         // TODO Needs to update persistent storage
@@ -1005,25 +913,37 @@ exit:
     return ret;
 }
 
-OCStackResult DeInitACLResource()
+/**
+ * Perform cleanup for ACL resources.
+ *
+ * @retval  none
+ */
+void DeInitACLResource()
 {
-    OCStackResult ret =  OCDeleteResource(gAclHandle);
+    OCDeleteResource(gAclHandle);
     gAclHandle = NULL;
 
-    if (gAcl)
-    {
-        DeleteACLList(gAcl);
-        gAcl = NULL;
-    }
-    return ret;
+    DeleteACLList(gAcl);
+    gAcl = NULL;
 }
 
+/**
+ * This method is used by PolicyEngine to retrieve ACL for a Subject.
+ *
+ * @param subjectId ID of the subject for which ACL is required.
+ * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
+ *                successive calls for same subjectId.
+ *
+ * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
+ *
+ * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL
+ */
 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr)
 {
     OicSecAcl_t *acl = NULL;
     OicSecAcl_t *begin = NULL;
 
-    if (NULL == subjectId)
+    if ( NULL == subjectId)
     {
         return NULL;
     }
@@ -1067,36 +987,31 @@ const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **
     return NULL;
 }
 
-OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
+
+OCStackResult InstallNewACL(const char* newJsonStr)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Convert CBOR format to ACL data. This will also validate the ACL data received.
-    OicSecAcl_t* newAcl = CBORPayloadToAcl(cborPayload, size);
+    // Convert JSON ACL data into binary. This will also validate the ACL data received.
+    OicSecAcl_t* newAcl = JSONToAclBin(newJsonStr);
 
     if (newAcl)
     {
         // Append the new ACL to existing ACL
         LL_APPEND(gAcl, newAcl);
 
-        // Update persistent storage only if it is not WILDCARD_SUBJECT_ID
-        if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
-            || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
-        {
-            ret = OC_STACK_OK;
-        }
-        else
+        // Convert ACL data into JSON for update to persistent storage
+        char *jsonStr = BinToAclJSON(gAcl);
+        if (jsonStr)
         {
-            size_t size = 0;
-            uint8_t *payload = NULL;
-            if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
+            cJSON *jsonAcl = cJSON_Parse(jsonStr);
+            OICFree(jsonStr);
+
+            if (jsonAcl)
             {
-                if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
-                {
-                    ret = OC_STACK_OK;
-                }
-                OICFree(payload);
+                ret = UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl);
             }
+            cJSON_Delete(jsonAcl);
         }
     }
 
@@ -1106,7 +1021,7 @@ OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
 /**
  * This function generates default ACL for security resource in case of owned status.
  *
- * @return Default ACL for security resource.
+ * @retval Default ACL for security resource.
  */
 static OicSecAcl_t* GetSecDefaultACL()
 {
@@ -1214,20 +1129,27 @@ OCStackResult UpdateDefaultSecProvACL()
              *      resources :  '/oic/sec/doxm', '/oic/sec/pstat'
              *      permission : READ
              */
-            OicSecAcl_t *newDefaultAcl = GetSecDefaultACL();
-            if (newDefaultAcl)
+            OicSecAcl_tnewDefaultAcl = GetSecDefaultACL();
+            if(newDefaultAcl)
             {
                 LL_APPEND(gAcl, newDefaultAcl);
 
-                size_t size = 0;
-                uint8_t *payload = NULL;
-                if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
+                char *jsonStr = BinToAclJSON(gAcl);
+                if(jsonStr)
                 {
-                    if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
+                    cJSON *jsonAcl = cJSON_Parse(jsonStr);
+                    OICFree(jsonStr);
+
+                    //Update SVR DB
+                    if (jsonAcl)
                     {
-                        ret = OC_STACK_OK;
+                        ret = UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl);
+                        if(OC_STACK_OK != ret)
+                        {
+                            OIC_LOG(WARNING, TAG, "Failed to update SVR DB");
+                        }
                     }
-                    OICFree(payload);
+                    cJSON_Delete(jsonAcl);
                 }
             }
         }
index 3671549..63aef6a 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+
 #include <stdlib.h>
 #include <string.h>
+#include "ocstack.h"
+#include "logger.h"
 #include "oic_malloc.h"
-#include "ocpayload.h"
-#include "payload_logging.h"
-#include "psinterface.h"
+#include "oic_string.h"
+#include "cJSON.h"
+#include "base64.h"
 #include "resourcemanager.h"
+#include "psinterface.h"
 #include "utlist.h"
 #include "srmresourcestrings.h"
-#include "srmutility.h"
 #include "amaclresource.h"
+#include "srmutility.h"
+#include <stdlib.h>
+#include <string.h>
 
 #define TAG  "SRM-AMACL"
 
-/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
- * The value of payload size is increased until reaching belox max cbor size. */
-static const uint8_t CBOR_SIZE = 255;
-
-/* Max cbor size payload. */
-static const uint16_t CBOR_MAX_SIZE = 4400;
-
-/** AMACL Map size - Number of mandatory items. */
-static const uint8_t AMACL_MAP_SIZE = 3;
-
-static OicSecAmacl_t *gAmacl = NULL;
+OicSecAmacl_t *gAmacl = NULL;
 static OCResourceHandle gAmaclHandle = NULL;
 
 void DeleteAmaclList(OicSecAmacl_t* amacl)
@@ -73,318 +69,193 @@ void DeleteAmaclList(OicSecAmacl_t* amacl)
     }
 }
 
-static size_t OicSecAmaclCount(const OicSecAmacl_t *secAmacl)
-{
-    size_t size = 0;
-    for (const OicSecAmacl_t *amacl = secAmacl; amacl; amacl = amacl->next)
-    {
-        size++;
-    }
-    return size;
-}
-
-OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amaclS, uint8_t **cborPayload,
-                                 size_t *cborSize)
+/*
+ * This internal method converts AMACL data into JSON format.
+ *
+ * Note: Caller needs to invoke 'free' when finished using the return string.
+ */
+char * BinToAmaclJSON(const OicSecAmacl_t * amacl)
 {
-    if (NULL == amaclS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
+    cJSON *jsonRoot = NULL;
+    char *jsonStr = NULL;
 
-    OCStackResult ret = OC_STACK_ERROR;
-    size_t cborLen = *cborSize;
-    if (0 == cborLen)
+    if (amacl)
     {
-        cborLen = CBOR_SIZE;
-    }
-
-    *cborSize = 0;
-    *cborPayload = NULL;
+        jsonRoot = cJSON_CreateObject();
+        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder amaclArray = { {.ptr = NULL }, .end = 0 };
-    CborError cborEncoderResult = CborNoError;
+        cJSON *jsonAmaclArray = NULL;
+        cJSON_AddItemToObject (jsonRoot, OIC_JSON_AMACL_NAME, jsonAmaclArray = cJSON_CreateArray());
+        VERIFY_NON_NULL(TAG, jsonAmaclArray, ERROR);
 
-    const OicSecAmacl_t *amacl = amaclS;
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
-
-    // Create AMACL Array
-    cborEncoderResult = cbor_encoder_create_array(&encoder, &amaclArray, OicSecAmaclCount(amacl));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMACL Array.");
+        while(amacl)
+        {
+            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
 
-    while (amacl)
-    {
-        CborEncoder amaclMap = { {.ptr = NULL }, .end = 0 };
-        cborEncoderResult = cbor_encoder_create_map(&amaclArray, &amaclMap, AMACL_MAP_SIZE);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMACL MAP.");
+            cJSON *jsonAmacl = cJSON_CreateObject();
 
-        // Resources -- Mandatory
-        {
-            CborEncoder resources = { {.ptr = NULL }, .end = 0};
-            cborEncoderResult = cbor_encode_text_string(&amaclMap, OIC_JSON_RESOURCES_NAME,
-                strlen(OIC_JSON_RESOURCES_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Name Tag.");
-            cborEncoderResult = cbor_encoder_create_array(&amaclMap, &resources, amacl->resourcesLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Name Array.");
-            for (size_t i = 0; i < amacl->resourcesLen; i++)
+            // Resources -- Mandatory
+            cJSON *jsonRsrcArray = NULL;
+            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_RESOURCES_NAME, jsonRsrcArray =
+                    cJSON_CreateArray());
+            VERIFY_NON_NULL(TAG, jsonRsrcArray, ERROR);
+            for (unsigned int i = 0; i < amacl->resourcesLen; i++)
             {
-                cborEncoderResult = cbor_encode_text_string(&resources, amacl->resources[i],
-                    strlen(amacl->resources[i]));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Name Value in Array.");
-
+                cJSON_AddItemToArray(jsonRsrcArray, cJSON_CreateString(amacl->resources[i]));
             }
-            cborEncoderResult = cbor_encoder_close_container(&amaclMap, &resources);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name ");
-        }
-        // Amss -- Mandatory
-        {
-            CborEncoder amss = { {.ptr = NULL }, .end = 0 };
-            cborEncoderResult = cbor_encode_text_string(&amaclMap, OIC_JSON_AMSS_NAME,
-                strlen(OIC_JSON_AMSS_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMSS Name Tag.");
-            cborEncoderResult = cbor_encoder_create_array(&amaclMap, &amss, amacl->amssLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMSS Name Array.");
-            for (size_t i = 0; i < amacl->amssLen; i++)
+
+            // Amss -- Mandatory
+            cJSON *jsonAmsArray = NULL;
+            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_AMSS_NAME, jsonAmsArray =
+                    cJSON_CreateArray());
+            VERIFY_NON_NULL(TAG, jsonAmsArray, ERROR);
+            for (unsigned int i = 0; i < amacl->amssLen; i++)
             {
-                cborEncoderResult = cbor_encode_byte_string(&amss, amacl->amss[i].id,
-                    sizeof(amacl->amss[i].id));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMSS Name Value.");
+                outLen = 0;
+
+                b64Ret = b64Encode(amacl->amss[i].id, sizeof(((OicUuid_t*) 0)->id), base64Buff,
+                        sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+
+                cJSON_AddItemToArray(jsonAmsArray, cJSON_CreateString(base64Buff));
             }
-            cborEncoderResult = cbor_encoder_close_container(&amaclMap, &amss);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing AMSS Array.");
-        }
-        // Owners -- Mandatory
-        {
-            cborEncoderResult = cbor_encode_text_string(&amaclMap, OIC_JSON_OWNERS_NAME,
-                strlen(OIC_JSON_OWNERS_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Owners Array Tag.");
-            CborEncoder owners = { {.ptr = NULL }, .end = 0};
-            cborEncoderResult = cbor_encoder_create_array(&amaclMap, &owners, amacl->ownersLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Owners Array.");
-            for (size_t i = 0; i < amacl->ownersLen; i++)
+
+            // Owners -- Mandatory
+            cJSON *jsonOwnrArray = NULL;
+            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_OWNERS_NAME, jsonOwnrArray =
+                    cJSON_CreateArray());
+            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
+            for (unsigned int i = 0; i < amacl->ownersLen; i++)
             {
-                cborEncoderResult = cbor_encode_byte_string(&owners, (uint8_t *)amacl->owners[i].id,
-                    sizeof(amacl->owners[i].id));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Owners Array Value.");
+                outLen = 0;
+
+                b64Ret = b64Encode(amacl->owners[i].id, sizeof(((OicUuid_t*) 0)->id), base64Buff,
+                        sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+
+                cJSON_AddItemToArray(jsonOwnrArray, cJSON_CreateString(base64Buff));
             }
-            cborEncoderResult = cbor_encoder_close_container(&amaclMap, &owners);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Owners Array.");
-        }
-        cborEncoderResult = cbor_encoder_close_container(&amaclArray, &amaclMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing AMACL Map.");
 
-        amacl = amacl->next;
-    }
-    cborEncoderResult = cbor_encoder_close_container(&encoder, &amaclArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Amacl Array.");
+            // Attach current amacl node to Amacl Array
+            cJSON_AddItemToArray(jsonAmaclArray, jsonAmacl);
+            amacl = amacl->next;
+        }
 
-    if (CborNoError == cborEncoderResult)
-    {
-        *cborPayload = outPayload;
-        *cborSize = encoder.ptr - outPayload;
-        ret = OC_STACK_OK;
+        jsonStr = cJSON_PrintUnformatted(jsonRoot);
     }
 
 exit:
-    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    if (jsonRoot)
     {
-       // reallocate and try again!
-       OICFree(outPayload);
-       outPayload = NULL;
-       // Since the allocated initial memory failed, double the memory.
-       cborLen += encoder.ptr - encoder.end;
-       cborEncoderResult = CborNoError;
-       ret = AmaclToCBORPayload(amaclS, cborPayload, &cborLen);
-       if (OC_STACK_OK == ret)
-       {
-           *cborSize = cborLen;
-           ret = OC_STACK_OK;
-       }
+        cJSON_Delete(jsonRoot);
     }
-
-    if (CborNoError != cborEncoderResult)
-    {
-       OICFree(outPayload);
-       outPayload = NULL;
-       *cborSize = 0;
-       *cborPayload = NULL;
-       ret = OC_STACK_ERROR;
-    }
-
-    return ret;
+    return jsonStr;
 }
 
-OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
-                                 OicSecAmacl_t **secAmacl)
-{
-    if (NULL == cborPayload || NULL == secAmacl || NULL != *secAmacl)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
 
-    *secAmacl = NULL;
 
+
+/*
+ * This internal method converts JSON AMACL into binary AMACL.
+ */
+OicSecAmacl_t * JSONToAmaclBin(const char * jsonStr)
+{
     OCStackResult ret = OC_STACK_ERROR;
+    OicSecAmacl_t * headAmacl = NULL;
+    OicSecAmacl_t * prevAmacl = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonAmaclArray = NULL;
 
-    CborValue amaclCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    int cborLen = size;
-    if (0 == size)
-    {
-        cborLen = CBOR_SIZE;
-    }
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &amaclCbor);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
-    OicSecAmacl_t *headAmacl = NULL;
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborValue amaclArray = { .parser = NULL };
-    cborFindResult = cbor_value_enter_container(&amaclCbor, &amaclArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+    jsonAmaclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
+    VERIFY_NON_NULL(TAG, jsonAmaclArray, INFO);
 
-    while (cbor_value_is_valid(&amaclArray))
+    if (cJSON_Array == jsonAmaclArray->type)
     {
-        CborValue amaclMap = { .parser = NULL };
-        cborFindResult = cbor_value_enter_container(&amaclArray, &amaclMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+        int numAmacl = cJSON_GetArraySize(jsonAmaclArray);
+        int idx = 0;
 
-        OicSecAmacl_t *amacl = (OicSecAmacl_t *) OICCalloc(1, sizeof(*amacl));
-        VERIFY_NON_NULL(TAG, amacl, ERROR);
-
-        while (cbor_value_is_valid(&amaclMap))
+        VERIFY_SUCCESS(TAG, numAmacl > 0, INFO);
+        do
         {
-            char *name = NULL;
-            size_t len = 0;
-            cborFindResult = cbor_value_dup_text_string(&amaclMap, &name, &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-            cborFindResult = cbor_value_advance(&amaclMap);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+            cJSON *jsonAmacl = cJSON_GetArrayItem(jsonAmaclArray, idx);
+            VERIFY_NON_NULL(TAG, jsonAmacl, ERROR);
 
-            CborType type = cbor_value_get_type(&amaclMap);
+            OicSecAmacl_t *amacl = (OicSecAmacl_t*)OICCalloc(1, sizeof(OicSecAmacl_t));
+            VERIFY_NON_NULL(TAG, amacl, ERROR);
 
-            // Resources -- Mandatory
-            if (0 == strcmp(OIC_JSON_RESOURCES_NAME, name))
+            headAmacl = (headAmacl) ? headAmacl : amacl;
+            if (prevAmacl)
             {
-                CborValue resources = { .parser = NULL  };
-                cborFindResult = cbor_value_get_array_length(&amaclMap, &amacl->resourcesLen);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-
-                cborFindResult = cbor_value_enter_container(&amaclMap, &resources);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-
-                amacl->resources = (char **) OICMalloc(amacl->resourcesLen * sizeof(*amacl->resources));
-                VERIFY_NON_NULL(TAG, amacl->resources, ERROR);
-                int i = 0;
-                while (cbor_value_is_text_string(&resources))
-                {
-                    cborFindResult = cbor_value_dup_text_string(&resources, &amacl->resources[i++],
-                        &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                    cborFindResult = cbor_value_advance(&resources);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                }
+                prevAmacl->next = amacl;
             }
 
-            // Amss -- Mandatory
-            if (0 == strcmp(OIC_JSON_AMSS_NAME, name))
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
+
+            // Resources -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_RESOURCES_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            amacl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, amacl->resourcesLen > 0, ERROR);
+            amacl->resources = (char**)OICCalloc(amacl->resourcesLen, sizeof(char*));
+            VERIFY_NON_NULL(TAG, (amacl->resources), ERROR);
+
+            size_t idxx = 0;
+            do
             {
-                CborValue amss = { .parser = NULL };
-                cborFindResult = cbor_value_get_array_length(&amaclMap, &amacl->amssLen);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                cborFindResult = cbor_value_enter_container(&amaclMap, &amss);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                int i = 0;
-                amacl->amss = (OicUuid_t *)OICCalloc(amacl->amssLen, sizeof(*amacl->amss));
-                VERIFY_NON_NULL(TAG, amacl->amss, ERROR);
-                while (cbor_value_is_valid(&amss))
-                {
-                    uint8_t *amssId = NULL;
-                    cborFindResult = cbor_value_dup_byte_string(&amss, &amssId, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                    cborFindResult = cbor_value_advance(&amss);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                    memcpy(amacl->amss[i].id, amssId, len);
-                    OICFree(amssId);
-                }
-            }
+                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
+
+                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
+                amacl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, (amacl->resources[idxx]), ERROR);
+                OICStrcpy(amacl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
+            } while ( ++idxx < amacl->resourcesLen);
+
+            // Amss -- Mandatory
+            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_AMSS_NAME,
+                               &(amacl->amssLen), &(amacl->amss)), ERROR);
 
             // Owners -- Mandatory
-            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
-            {
-                CborValue owners = { .parser = NULL };
-                cborFindResult = cbor_value_get_array_length(&amaclMap, &amacl->ownersLen);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                cborFindResult = cbor_value_enter_container(&amaclMap, &owners);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                int i = 0;
-                amacl->owners = (OicUuid_t *)OICCalloc(amacl->ownersLen, sizeof(*amacl->owners));
-                VERIFY_NON_NULL(TAG, amacl->owners, ERROR);
-                while (cbor_value_is_valid(&owners))
-                {
-                    uint8_t *owner = NULL;
-                    cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                    cborFindResult = cbor_value_advance(&owners);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                    memcpy(amacl->owners[i].id, owner, len);
-                    OICFree(owner);
-                }
-            }
-            if (CborMapType != type && cbor_value_is_valid(&amaclMap))
-            {
-                cborFindResult = cbor_value_advance(&amaclMap);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-            }
-            OICFree(name);
-        }
+            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_OWNERS_NAME,
+                               &(amacl->ownersLen), &(amacl->owners)), ERROR);
 
-        amacl->next = NULL;
-        if (NULL == headAmacl)
-        {
-            headAmacl = amacl;
-        }
-        else
-        {
-            OicSecAmacl_t *temp = headAmacl;
-            while (temp->next)
-            {
-                temp = temp->next;
-            }
-            temp->next = amacl;
-        }
-        if (cbor_value_is_valid(&amaclArray))
-        {
-            cborFindResult = cbor_value_advance(&amaclArray);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-        }
+            prevAmacl = amacl;
+        } while( ++idx < numAmacl);
     }
-    *secAmacl = headAmacl;
+
     ret = OC_STACK_OK;
+
 exit:
-    if (CborNoError != cborFindResult)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
         DeleteAmaclList(headAmacl);
         headAmacl = NULL;
-        ret = OC_STACK_ERROR;
     }
-    return ret;
+    return headAmacl;
 }
 
 static OCEntityHandlerResult HandleAmaclGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
     // Convert Amacl data into JSON for transmission
-    size_t size = 0;
-    uint8_t *cborPayload = NULL;
-    OCStackResult res = AmaclToCBORPayload(gAmacl, &cborPayload, &size);
+    char* jsonStr = BinToAmaclJSON(gAmacl);
 
-    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
 
     // Send response payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, cborPayload);
+    SendSRMResponse(ehRequest, ehRet, jsonStr);
 
-    OICFree(cborPayload);
+    OICFree(jsonStr);
 
     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
@@ -394,44 +265,44 @@ static OCEntityHandlerResult HandleAmaclPostRequest (const OCEntityHandlerReques
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    // Convert CBOR Amacl data into binary. This will also validate the Amacl data received.
-    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;;
-    if (payload)
+    // Convert JSON Amacl data into binary. This will also validate the Amacl data received.
+    OicSecAmacl_t* newAmacl = JSONToAmaclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if (newAmacl)
     {
-        OicSecAmacl_t *newAmacl = NULL;
-        OCStackResult res = CBORPayloadToAmacl(payload, CBOR_SIZE, &newAmacl);
-        if (newAmacl && OC_STACK_OK == res)
+        // Append the new Amacl to existing Amacl
+        LL_APPEND(gAmacl, newAmacl);
+
+        // Convert Amacl data into JSON for update to persistent storage
+        char *jsonStr = BinToAmaclJSON(gAmacl);
+        if (jsonStr)
         {
-            // Append the new Amacl to existing Amacl
-            LL_APPEND(gAmacl, newAmacl);
-            size_t size = 0;
-            // Convert Amacl data into JSON for update to persistent storage.
-            uint8_t *cborPayload = NULL;
-            res = AmaclToCBORPayload(gAmacl, &cborPayload, &size);
-            if (cborPayload && (OC_STACK_OK == res) &&
-                (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_AMACL_NAME, cborPayload, size)))
+            cJSON *jsonAmacl = cJSON_Parse(jsonStr);
+            OICFree(jsonStr);
+
+            if ((jsonAmacl) &&
+                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_AMACL_NAME, jsonAmacl)))
             {
                 ehRet = OC_EH_RESOURCE_CREATED;
             }
-            OICFree(cborPayload);
+            cJSON_Delete(jsonAmacl);
         }
-        OICFree(payload);
     }
 
     // Send payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, NULL);
+    SendSRMResponse(ehRequest, ehRet, NULL);
 
-    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-/**
+/*
  * This internal method is the entity handler for Amacl resources and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-static OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
-                                                 OCEntityHandlerRequest * ehRequest,
-                                                 void* callbackParameter)
+OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
+                                          OCEntityHandlerRequest * ehRequest,
+                                          void* callbackParameter)
 {
     (void) callbackParameter;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
@@ -463,18 +334,20 @@ static OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
     return ehRet;
 }
 
-/**
+/*
  * This internal method is used to create '/oic/sec/amacl' resource.
  */
-static OCStackResult CreateAmaclResource()
+OCStackResult CreateAmaclResource()
 {
-    OCStackResult ret = OCCreateResource(&gAmaclHandle,
-                                         OIC_RSRC_TYPE_SEC_AMACL,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_AMACL_URI,
-                                         AmaclEntityHandler,
-                                         NULL,
-                                         OC_OBSERVABLE);
+    OCStackResult ret;
+
+    ret = OCCreateResource(&gAmaclHandle,
+                           OIC_RSRC_TYPE_SEC_AMACL,
+                           OIC_MI_DEF,
+                           OIC_RSRC_AMACL_URI,
+                           AmaclEntityHandler,
+                           NULL,
+                           OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
@@ -484,24 +357,23 @@ static OCStackResult CreateAmaclResource()
     return ret;
 }
 
+/**
+ * Initialize Amacl resource by loading data from persistent storage.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult InitAmaclResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    uint8_t *data = NULL;
-    size_t size = 0;
-    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_AMACL_NAME, &data, &size);
+    // Read Amacl resource from PS
+    char* jsonSVRDatabase = GetSVRDatabase();
 
-    // If database read failed
-    if (OC_STACK_OK != ret)
-    {
-        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
-    if (data)
+    if (jsonSVRDatabase)
     {
-        // Read AMACL resource from PS
-        ret = CBORPayloadToAmacl(data, size, &gAmacl);
-        OICFree(data);
+        // Convert JSON Amacl into binary format
+        gAmacl = JSONToAmaclBin(jsonSVRDatabase);
+        OICFree(jsonSVRDatabase);
     }
 
     // Instantiate 'oic/sec/amacl' resource
@@ -514,6 +386,11 @@ OCStackResult InitAmaclResource()
     return ret;
 }
 
+/**
+ * Perform cleanup for Amacl resources.
+ *
+ * @retval  none
+ */
 void DeInitAmaclResource()
 {
     OCDeleteResource(gAmaclHandle);
@@ -523,6 +400,7 @@ void DeInitAmaclResource()
     gAmacl = NULL;
 }
 
+
 OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
 {
     OicSecAmacl_t *amacl = NULL;
@@ -534,7 +412,7 @@ OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
     {
         for(size_t i = 0; i < amacl->resourcesLen; i++)
         {
-            if (0 == strncmp((amacl->resources[i]), resource, strlen(amacl->resources[i])))
+            if (strncmp((amacl->resources[i]), resource, strlen(amacl->resources[i])) == 0)
             {
                 //Returning the ID of the first AMS service for the resource
                 memcpy(amsDeviceId, &amacl->amss[0], sizeof(*amsDeviceId));
index ed6d9e2..c9be755 100644 (file)
@@ -18,7 +18,6 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <string.h>
 #include "oic_malloc.h"
 #include "amsmgr.h"
 #include "resourcemanager.h"
 #include "policyengine.h"
 #include "oic_string.h"
 #include "caremotehandler.h"
+#include <string.h>
 
 #define TAG "SRM-AMSMGR"
 
+
  //Callback for AMS service multicast discovery request.
 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
                          OCClientResponse * clientResponse);
@@ -50,6 +51,7 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
     OCClientResponse * clientResponse);
 
+
 OCStackResult DiscoverAmsService(PEContext_t *context)
 {
     OIC_LOG(INFO, TAG, "IN DiscoverAmsService");
@@ -87,6 +89,7 @@ exit:
     return ret;
 }
 
+
 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
                          OCClientResponse * clientResponse)
 {
@@ -111,16 +114,15 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     }
 
     OicSecDoxm_t *doxm = NULL;
-
     OIC_LOG_V(INFO, TAG, "Doxm DeviceId Discovery response = %s\n",
-          ((OCSecurityPayload*)clientResponse->payload)->securityData1);
-    uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData1;
+          ((OCSecurityPayload*)clientResponse->payload)->securityData);
+    doxm = JSONToDoxmBin(((OCSecurityPayload*)clientResponse->payload)->securityData);
 
     //As doxm is NULL amsmgr can't test if response from trusted AMS service
     //so keep the transaction.
-    if (OC_STACK_OK == CBORPayloadToDoxm(payload, 0, &doxm))
+    if(NULL == doxm)
     {
-        OIC_LOG_V(ERROR, TAG, "%s : Unable to convert CBOR to Binary",__func__);
+        OIC_LOG_V(ERROR, TAG, "%s : Unable to convert JSON to Binary",__func__);
         return OC_STACK_KEEP_TRANSACTION;
     }
 
@@ -136,7 +138,7 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     {
         OIC_LOG(INFO, TAG, "AMS Manager Sending unicast discovery to get secured port info");
         //Sending Unicast discovery to get secure port information
-        if (OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
+        if(OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
                 clientResponse->connType))
         {
             context->retVal = ACCESS_WAITING_FOR_AMS;
@@ -148,6 +150,7 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     return OC_STACK_DELETE_TRANSACTION;
 }
 
+
 OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
                                       OCConnectivityType connType)
 {
@@ -195,7 +198,7 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
         return OC_STACK_DELETE_TRANSACTION;
     }
 
-    OCResourcePayload *resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+    OCResourcePayloadresPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
 
     //Verifying if the ID of the sender is an AMS service that this device trusts.
     if(resPayload &&
@@ -225,6 +228,7 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
     return OC_STACK_DELETE_TRANSACTION;
 }
 
+
 OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
         uint16_t securedPort)
 {
@@ -265,6 +269,7 @@ exit:
     return ret;
 }
 
+
 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
     OCClientResponse * clientResponse)
 {
@@ -300,9 +305,8 @@ static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handl
         memcmp(context->amsMgrContext->amsDeviceId.id, clientResponse->identity.id,
                        sizeof(context->amsMgrContext->amsDeviceId.id)) == 0)
     {
-        size_t size = strlen((char *)clientResponse->payload);
         OCStackResult ret =
-                InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData1, size);
+                InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData);
         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
 
         OIC_LOG_V(INFO, TAG, "%s : Calling checkPermission", __func__);
@@ -321,6 +325,7 @@ exit:
     return OC_STACK_DELETE_TRANSACTION;
 }
 
+
 OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
                         const CARequestInfo_t *requestInfo)
 {
@@ -328,7 +333,7 @@ OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endp
 
     //The AmsMgr context endpoint and requestInfo will be free from ,
     //AmsMgrAclReqCallback function
-    if (context->amsMgrContext->endpoint)
+    if(context->amsMgrContext->endpoint)
     {
         OICFree(context->amsMgrContext->endpoint);
         context->amsMgrContext->endpoint = NULL;
@@ -337,7 +342,7 @@ OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endp
     VERIFY_NON_NULL(TAG, context->amsMgrContext->endpoint, ERROR);
     *context->amsMgrContext->endpoint = *endpoint;
 
-    if (context->amsMgrContext->requestInfo)
+    if(context->amsMgrContext->requestInfo)
     {
         FreeCARequestInfo(context->amsMgrContext->requestInfo);
         context->amsMgrContext->requestInfo = NULL;
@@ -351,7 +356,7 @@ exit:
 
 void FreeCARequestInfo(CARequestInfo_t *requestInfo)
 {
-    if (NULL == requestInfo)
+    if(NULL == requestInfo)
     {
         OIC_LOG_V(ERROR, TAG, "%s: Can't free memory. Received NULL requestInfo", __func__);
         return;
@@ -375,7 +380,7 @@ bool FoundAmaclForRequest(PEContext_t *context)
     memset(&context->amsMgrContext->amsDeviceId, 0, sizeof(context->amsMgrContext->amsDeviceId));
 
     //Call amacl resource function to get the AMS service deviceID for the resource
-    if (OC_STACK_OK == AmaclGetAmsDeviceId(context->resource, &context->amsMgrContext->amsDeviceId))
+    if(OC_STACK_OK == AmaclGetAmsDeviceId(context->resource, &context->amsMgrContext->amsDeviceId))
     {
         OIC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
                 __func__, context->resource);
@@ -392,11 +397,12 @@ bool FoundAmaclForRequest(PEContext_t *context)
      return ret;
 }
 
+
 void ProcessAMSRequest(PEContext_t *context)
 {
     OicUuid_t  emptyUuid = {.id={}};
     OIC_LOG_V(INFO, TAG, "Entering %s", __func__);
-    if (NULL != context)
+    if(NULL != context)
     {
         if((false == context->matchingAclFound) && (false == context->amsProcessing))
         {
index b77c4e5..2a1ac98 100644 (file)
@@ -1,38 +1,38 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * 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.
+ *
+ ******************************************************************/
 
 #include "base64.h"
 
-/** base character of Base64. */
+/**< base character of Base64  */
 static const char g_b64TransTbl[] =
                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"\
                 "ghijklmnopqrstuvwxyz0123456789+/";
 
 /**
- * base64 block encode function.
+ * base64 block encode function
  *
- * @param in is the octet stream, max 3 byte.
- * @param out is the Base64 encoded stream, 4 byte.
- * @param len is the  byte-length of octet stream.
+ * @param[in] in  octet stream, max 3 byte
+ * @param[out] out  base64 encoded stream, 4 byte
+ * @param[in] len  byte-length of in
  *
- * @return ::B64_OK for Success, otherwise some error value.
+ * @return  B64_OK for Success, otherwise some error value
  */
 static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
 {
@@ -43,7 +43,7 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
 
     out[0] = g_b64TransTbl[in[0] >> 2];
 
-    if (1 == len)
+    if(1 == len)
     {
         out[1] = g_b64TransTbl[((in[0] & 0x03) << 4)];
     }
@@ -52,7 +52,7 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
         out[1] = g_b64TransTbl[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
     }
 
-    if (2 == len)
+    if(2 == len)
     {
         out[2] = g_b64TransTbl[((in[1] & 0x0f) << 2)];
     }
@@ -77,9 +77,25 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
     return B64_OK;
 }
 
+/**
+ * Encode the plain message in base64.
+ *
+ * @param[in] in  Plain message
+ * @param[in] inLen  Byte length of 'in'
+ * @param[in,out] outBuf Output buffer
+ *                Base64 encoded message will be written into 'out'
+ *                NOTE : This method adds a NULL to the string configuration
+ * @param[in] outBufSize Size of output buffer
+ * @param[out] outLen  Byte length of encoded message
+ *
+ * @return  B64_OK for Success, otherwise some error value
+*/
 B64Result b64Encode(const uint8_t* in, const size_t inLen,
                char* outBuf, const size_t outBufSize, uint32_t* outLen)
 {
+    size_t i;
+    size_t minBufSize;
+
     if (NULL == in || 0 == inLen || NULL ==  outBuf || NULL == outLen )
     {
         return B64_INVALID_PARAM;
@@ -88,13 +104,12 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
     *outLen = ((inLen / 3) * 3 == inLen) ?
               ((inLen / 3) * 4) :
               (((inLen / 3) + 1) * 4);
-    uint32_t minBufSize = (*outLen + 1);
-    if (outBufSize < minBufSize)
+    minBufSize = (*outLen + 1);
+    if(outBufSize < minBufSize)
     {
         return B64_OUTPUT_BUFFER_TOO_SMALL;
     }
 
-    uint32_t i;
     for (i = 0; i < inLen / 3; i++)
     {
         if(B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, 3))
@@ -105,7 +120,7 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 
     if (i * 3 != inLen)
     {
-        if (B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, inLen - i * 3))
+        if(B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, inLen - i * 3))
         {
             return B64_INVALID_PARAM;
         }
@@ -117,11 +132,11 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 }
 
 /**
- * Get decoded value.
+ * Get decoded value
  *
- * @param c is the Base64 encoded character.
+ * @param[in] c  Base64 encoded charactor
  *
- * @return decoded value, 6-bit.
+ * @return decoded value, 6-bit
  */
 static uint32_t b64GetVal(char c)
 {
@@ -154,21 +169,23 @@ static uint32_t b64GetVal(char c)
 }
 
 /**
- * Base64 block decode function.
+ * base64 block decode function
  *
- * @param in is the Base64 encoded stream, 4 bytes.
- * @param out is the Octet stream, 3 bytes.
+ * @param[in] in  Base64 encoded stream, 4 bytes
+ * @param[out] out  Octet stream, 3 bytes
  *
- * @return ::B64_OK for Success, otherwise some error value.
+ * @return  B64_OK for Success, otherwise some error value
  */
 static B64Result b64DecodeBlk(const char* in, uint8_t* out)
 {
-    if (NULL == in || NULL == out)
+    uint32_t val;
+
+    if(NULL == in || NULL == out)
     {
         return B64_INVALID_PARAM;
     }
 
-    uint32_t val = (b64GetVal(in[0]) << 18) | (b64GetVal(in[1]) << 12) |
+    val = (b64GetVal(in[0]) << 18) | (b64GetVal(in[1]) << 12) |
           (b64GetVal(in[2]) << 6) | (b64GetVal(in[3]));
 
     out[0] = (val >> 16) & 0xff;
@@ -185,32 +202,47 @@ static B64Result b64DecodeBlk(const char* in, uint8_t* out)
     return B64_OK;
 }
 
+/**
+ * Decode the encoded message in base64.
+ *
+ * @param[in] in  Base64 encoded message
+ * @param[in] inLen  Byte lenth of 'in'
+ * @param[in, out] outBuf  Output buffer
+ *                 Base64 decoded message will be written into 'out'
+ * @param[in] outBufSize Size of output buffer
+ * @param[out] outLen  Byte length of decoded message
+ *
+ * @return  B64_OK for Success, otherwise some error value
+ */
 B64Result b64Decode(const char* in, const size_t inLen,
                uint8_t* outBuf, size_t outBufSize, uint32_t* outLen)
 {
+    uint32_t i;
+    uint32_t minBufSize;
+
     if (NULL == in || 0 == inLen || 0 != (inLen & 0x03) || NULL == outBuf || NULL == outLen)
     {
         return B64_INVALID_PARAM;
     }
 
     *outLen = (inLen / 4) * 3;
-    uint32_t minBufSize = (inLen / 4) * 3;
-    if ('=' == in[inLen - 1])
+    minBufSize = (inLen / 4) * 3;
+    if('=' == in[inLen - 1])
     {
         minBufSize--;
         (*outLen)--;
     }
-    if ('=' == in[inLen - 2])
+    if('=' == in[inLen - 2])
     {
         minBufSize--;
         (*outLen)--;
     }
-    if (outBufSize < minBufSize)
+    if(outBufSize < minBufSize)
     {
         return B64_OUTPUT_BUFFER_TOO_SMALL;
     }
 
-    for (uint32_t i = 0; i < inLen / 4; i++)
+    for (i = 0; i < inLen / 4; i++)
     {
         if(B64_OK != b64DecodeBlk(in + i * 4, outBuf + i * 3))
         {
index 70fb2b4..54f17b4 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #define __STDC_LIMIT_MACROS
-
-#include <stdlib.h>
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
-#include <strings.h>
-#endif
-#include <stdint.h>
-
-#include "cainterface.h"
-#include "payload_logging.h"
 #include "ocstack.h"
-#include "ocrandom.h"
-#include "ocserverrequest.h"
+#include "logger.h"
 #include "oic_malloc.h"
-#include "ocpayload.h"
+#include "cJSON.h"
+#include "resourcemanager.h"
+#include "psinterface.h"
 #include "utlist.h"
+#include "srmresourcestrings.h"
 #include "credresource.h"
+#include "ocrandom.h"
 #include "doxmresource.h"
-#include "pstatresource.h"
-#include "iotvticalendar.h"
-#include "pbkdf2.h"
-#include "resourcemanager.h"
-#include "srmresourcestrings.h"
+#include "base64.h"
 #include "srmutility.h"
-#include "psinterface.h"
-#include "pinoxmcommon.h"
+#include "cainterface.h"
+#include "pbkdf2.h"
+#include <stdlib.h>
+#include "iotvticalendar.h"
+#include "ocserverrequest.h"
 
 #ifdef __WITH_DTLS__
 #include "global.h"
+#endif //__WITH_DTLS__
+
+#ifdef WITH_ARDUINO
+#include <string.h>
+#else
+#include <strings.h>
 #endif
+#include <stdint.h>
 
 #define TAG  "SRM-CREDL"
 
-/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
- * The value of payload size is increased until reaching belox max cbor size. */
-static const uint8_t CBOR_SIZE = 255;
-
-/** Max cbor size payload. */
-static const uint16_t CBOR_MAX_SIZE = 4400;
-
-/** CRED Map size - Number of mandatory items. */
-static const uint8_t CRED_MAP_SIZE = 4;
 
 static OicSecCred_t        *gCred = NULL;
 static OCResourceHandle    gCredHandle = NULL;
@@ -73,7 +62,7 @@ static void FreeCred(OicSecCred_t *cred)
 {
     if(NULL == cred)
     {
-        OIC_LOG(ERROR, TAG, "Invalid Parameter");
+        OIC_LOG (ERROR, TAG, "Invalid Parameter");
         return;
     }
     //Note: Need further clarification on roleID data type
@@ -111,292 +100,244 @@ void DeleteCredList(OicSecCred_t* cred)
     }
 }
 
-static size_t OicSecCredCount(const OicSecCred_t *secCred)
+/**
+ * This function converts credential data into JSON format.
+ * Caller needs to invoke 'free' when done using
+ * returned string.
+ * @param cred  pointer to instance of OicSecCred_t structure.
+ *
+ * @retval
+ *      pointer to JSON credential representation - if credential for subjectId found
+ *      NULL                                      - if credential for subjectId not found
+ */
+char * BinToCredJSON(const OicSecCred_t * cred)
 {
-    size_t size = 0;
-    for (const OicSecCred_t *cred = secCred; cred; cred = cred->next)
-    {
-        size++;
-    }
-    return size;
-}
+    cJSON *jsonRoot = NULL;
+    char *jsonStr = NULL;
 
-OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
-                                size_t *cborSize)
-{
-    if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
+    if (cred)
     {
-        return OC_STACK_INVALID_PARAM;
-    }
+        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+        uint32_t outLen = 0;
+        B64Result b64Ret = B64_OK;
 
-    OCStackResult ret = OC_STACK_ERROR;
-    size_t cborLen = *cborSize;
-    if (0 == cborLen)
-    {
-        cborLen = CBOR_SIZE;
-    }
+        jsonRoot = cJSON_CreateObject();
+        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    *cborSize = 0;
-    *cborPayload = NULL;
+        cJSON *jsonCredArray = NULL;
+        cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
+                jsonCredArray = cJSON_CreateArray());
+        VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
 
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder credArray = { {.ptr = NULL }, .end = 0 };
-    CborError cborEncoderResult = CborNoError;
+        while(cred)
+        {
+            cJSON *jsonCred = cJSON_CreateObject();
+            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
 
-    const OicSecCred_t *cred = credS;
-    size_t mapSize = CRED_MAP_SIZE;
-    if (cred->period)
-    {
-        mapSize++;
-    }
-    if (cred->publicData.data)
-    {
-        mapSize++;
-    }
-    if (cred->privateData.data)
-    {
-        mapSize++;
-    }
-    if (cred->period)
-    {
-        mapSize++;
-    }
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+            //CredID -- Mandatory
+            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDID_NAME, (int)cred->credId);
 
-    // Create CRED Array
-    cborEncoderResult = cbor_encoder_create_array(&encoder, &credArray, OicSecCredCount(cred));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding0 Cred Array.");
+            //Subject -- Mandatory
+            outLen = 0;
+            memset(base64Buff, 0, sizeof(base64Buff));
+            b64Ret = b64Encode(cred->subject.id, sizeof(cred->subject.id), base64Buff,
+                   sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+            cJSON_AddStringToObject(jsonCred, OIC_JSON_SUBJECT_NAME, base64Buff);
 
-    while (cred)
-    {
-        CborEncoder credMap = { {.ptr = NULL }, .end = 0 };
-        cborEncoderResult = cbor_encoder_create_map(&credArray, &credMap, mapSize);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map");
-
-        //CredID -- Mandatory
-        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDID_NAME,
-            strlen(OIC_JSON_CREDID_NAME));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Tag. ");
-        cborEncoderResult = cbor_encode_int(&credMap, cred->credId);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Value.");
-
-        //Subject -- Mandatory
-        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_SUBJECT_NAME,
-            strlen(OIC_JSON_SUBJECT_NAME));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Tag.");
-        cborEncoderResult = cbor_encode_byte_string(&credMap, cred->subject.id,
-            sizeof(cred->subject.id));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Value.");
-
-        //CredType -- Mandatory
-        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDTYPE_NAME,
-            strlen(OIC_JSON_CREDTYPE_NAME));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag.");
-        cborEncoderResult = cbor_encode_int(&credMap, cred->credType);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
+            //Note: Need further clarification on roleID data type
+#if 0
+            //RoleId -- Not Mandatory
+            if(cred->roleIdsLen > 0)
+            {
+                cJSON *jsonRoleIdsArray = NULL;
+                cJSON_AddItemToObject (jsonCred, OIC_JSON_ROLEIDS_NAME,
+                                         jsonRoleIdsArray = cJSON_CreateArray());
+                VERIFY_NON_NULL(TAG, jsonRoleIdsArray, ERROR);
+                for (size_t i = 0; i < cred->roleIdsLen; i++)
+                {
+                    cJSON_AddItemToArray (jsonRoleIdsArray,
+                            cJSON_CreateString((char *)cred->roleIds[i].id));
+                }
+            }
+#endif
+
+            //CredType -- Mandatory
+            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDTYPE_NAME,(int)cred->credType);
 
 #ifdef __WITH_X509__
-        //PublicData -- Not Mandatory
-        if (cred->publicData.data)
-        {
-            cborEncoderResult = cbor_encode_text_string(&credMap,
-                OIC_JSON_PUBLICDATA_NAME, strlen(OIC_JSON_PUBLICDATA_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Data Tag.");
-            cborEncoderResult = cbor_encode_byte_string(&credMap, cred->publicData.data,
-                    sizeof(cred->publicData.data));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Tag Value.");
-        }
+            //PublicData -- Not Mandatory
+            if(cred->publicData.data)
+            {
+                if (SIGNED_ASYMMETRIC_KEY == cred->credType)
+                {
+                    cJSON_AddItemToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME,
+                                          cJSON_Parse(cred->publicData.data));
+                }
+                else
+                {
+                cJSON_AddStringToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME, cred->publicData.data);
+                }
+            }
 #endif /*__WITH_X509__*/
-        //PrivateData -- Not Mandatory
-        if(cred->privateData.data)
-        {
-            cborEncoderResult = cbor_encode_text_string(&credMap,
-                OIC_JSON_PRIVATEDATA_NAME, strlen(OIC_JSON_PRIVATEDATA_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Data Tag");
-            cborEncoderResult = cbor_encode_byte_string(&credMap, cred->privateData.data,
-                sizeof(cred->privateData.data));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Data Value.");
-        }
+            //PrivateData -- Not Mandatory
+            if(cred->privateData.data)
+            {
+#ifdef __WITH_X509__
+                if (SIGNED_ASYMMETRIC_KEY == cred->credType)
+                {
+                    cJSON_AddItemToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME,
+                                          cJSON_Parse(cred->privateData.data));
+                }
+                else
+                {
+                    cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
+                }
+#else
+                cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
+#endif
+            }
 
-        //Period -- Not Mandatory
-        if(cred->period)
-        {
-            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PERIOD_NAME,
-                strlen(OIC_JSON_PERIOD_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Tag.");
-            cborEncoderResult = cbor_encode_text_string(&credMap, cred->period,
-                strlen(cred->period));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Value.");
-        }
+            //Period -- Not Mandatory
+            if(cred->period)
+            {
+                cJSON_AddStringToObject(jsonCred, OIC_JSON_PERIOD_NAME,
+                                        cred->period);
+            }
 
-        //Owners -- Mandatory
-        {
-            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_OWNERS_NAME,
-                strlen(OIC_JSON_OWNERS_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Name Tag.");
-            CborEncoder owners = { {.ptr = NULL }, .end = 0 };
-            cborEncoderResult = cbor_encoder_create_array(&credMap, &owners, cred->ownersLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Name Array.");
+            //Owners -- Mandatory
+            cJSON *jsonOwnrArray = NULL;
+            cJSON_AddItemToObject (jsonCred, OIC_JSON_OWNERS_NAME,
+                                             jsonOwnrArray = cJSON_CreateArray());
+            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
             for (size_t i = 0; i < cred->ownersLen; i++)
             {
-                cborEncoderResult = cbor_encode_byte_string(&owners,
-                    (uint8_t *)cred->owners[i].id,
-                    sizeof(cred->owners[i].id));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Array Value.");
+                outLen = 0;
+                memset(base64Buff, 0, sizeof(base64Buff));
+                b64Ret = b64Encode(cred->owners[i].id, sizeof(cred->owners[i].id),
+                        base64Buff, sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+                cJSON_AddItemToArray (jsonOwnrArray,
+                                       cJSON_CreateString((char *)(base64Buff)));
             }
-            cborEncoderResult = cbor_encoder_close_container(&credMap, &owners);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Owners Name Array.");
-        }
-        cborEncoderResult = cbor_encoder_close_container(&credArray, &credMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
 
-        cred = cred->next;
-   }
-   cborEncoderResult = cbor_encoder_close_container(&encoder, &credArray);
-   VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Array.");
+            /* Attach current cred node to cred Array */
+            cJSON_AddItemToArray(jsonCredArray, jsonCred);
+            cred = cred->next;
+        }
 
-   if (CborNoError == cborEncoderResult)
-   {
-       *cborPayload = outPayload;
-       *cborSize = encoder.ptr - outPayload;
-        ret = OC_STACK_OK;
+        jsonStr = cJSON_PrintUnformatted(jsonRoot);
     }
 
 exit:
-    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
-    {
-       // reallocate and try again!
-       OICFree(outPayload);
-       outPayload = NULL;
-       // Since the allocated initial memory failed, double the memory.
-       cborLen += encoder.ptr - encoder.end;
-       cborEncoderResult = CborNoError;
-       ret = CredToCBORPayload(credS, cborPayload, &cborLen);
-       if (CborNoError == cborEncoderResult)
-       {
-           *cborSize = cborLen;
-            ret = OC_STACK_OK;
-        }
-    }
-
-    if (CborNoError != cborEncoderResult)
+    if (jsonRoot)
     {
-       OICFree(outPayload);
-       outPayload = NULL;
-       *cborSize = 0;
-       *cborPayload = NULL;
-       ret = OC_STACK_ERROR;
+        cJSON_Delete(jsonRoot);
     }
-
-    return ret;
+    return jsonStr;
 }
 
-OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
-                                OicSecCred_t **secCred)
+/*
+ * This internal method converts JSON cred into binary cred.
+ */
+OicSecCred_t * JSONToCredBin(const char * jsonStr)
 {
-    if (NULL == cborPayload || NULL == secCred || NULL != *secCred)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
-
-    *secCred = NULL;
-
     OCStackResult ret = OC_STACK_ERROR;
+    OicSecCred_t * headCred = NULL;
+    OicSecCred_t * prevCred = NULL;
+    cJSON *jsonCredArray = NULL;
 
-    CborValue credCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    OicSecCred_t *cred = NULL;
-    char *name = NULL;
-
-    int cborLen = size;
-    if (0 == size)
-    {
-        cborLen = CBOR_SIZE;
-    }
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &credCbor);
-
-    OicSecCred_t *headCred = NULL;
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborValue credArray = { .parser = NULL };
-    cborFindResult = cbor_value_enter_container(&credCbor, &credArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Array.");
-
-    while (cbor_value_is_valid(&credArray))
+    jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
+    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
+    if (cJSON_Array == jsonCredArray->type)
     {
-        CborValue credMap = { .parser = NULL };
-        cborFindResult = cbor_value_enter_container(&credArray, &credMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Map.");
+        int numCred = cJSON_GetArraySize(jsonCredArray);
+        int idx = 0;
 
-        cred = (OicSecCred_t *) OICCalloc(1, sizeof(*cred));
-        VERIFY_NON_NULL(TAG, cred, ERROR);
+        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+        uint32_t outLen = 0;
+        B64Result b64Ret = B64_OK;
 
-        while (cbor_value_is_valid(&credMap))
+        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
+        do
         {
-            size_t len = 0;
-            cborFindResult = cbor_value_dup_text_string(&credMap, &name, &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Name.");
-            cborFindResult = cbor_value_advance(&credMap);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Name. ");
+            cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
+            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
+
+            OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+            VERIFY_NON_NULL(TAG, cred, ERROR);
 
-            CborType type = cbor_value_get_type(&credMap);
+            headCred = (headCred) ? headCred : cred;
+            if (prevCred)
+            {
+                prevCred->next = cred;
+            }
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
 
             //CredId -- Mandatory
-            if (0 == strcmp(OIC_JSON_CREDID_NAME, name))
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
+            if(jsonObj)
             {
-                cborFindResult = cbor_value_get_int(&credMap, (int *) &cred->credId);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Id Value.");
+                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+                cred->credId = jsonObj->valueint;
             }
+
             //subject -- Mandatory
-            if (0 == strcmp(OIC_JSON_SUBJECT_NAME, name))
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            outLen = 0;
+            memset(base64Buff, 0, sizeof(base64Buff));
+            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
+                    base64Buff, sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(cred->subject.id)),
+                           ERROR);
+            memcpy(cred->subject.id, base64Buff, outLen);
+
+            //CredType -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            cred->credType = (OicSecCredType_t)jsonObj->valueint;
+
+            //PrivateData is mandatory for some of the credential types listed below.
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
+            if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
+                (cred->credType & SYMMETRIC_GROUP_KEY) ||
+                (cred->credType & PIN_PASSWORD))
             {
-                uint8_t *id = NULL;
-                cborFindResult = cbor_value_dup_byte_string(&credMap, &id, &len, NULL);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Subject Name Value.");
-                memcpy(cred->subject.id, id, len);
-                OICFree(id);
+                if(jsonObj)
+                {
+                    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+                }
             }
-            //CredType -- Mandatory
-            if (0 == strcmp(OIC_JSON_CREDTYPE_NAME, name))
+#ifdef __WITH_X509__
+            else if (cred->credType & SIGNED_ASYMMETRIC_KEY)
             {
-                cborFindResult = cbor_value_get_int(&credMap, (int *) &cred->credType);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Type Value.");
+                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
             }
-            //Owners -- Mandatory
-            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
+#endif //  __WITH_X509__
+            if (NULL != jsonObj)
             {
-                CborValue owners = { .parser = NULL };
-                cborFindResult = cbor_value_get_array_length(&credMap, &cred->ownersLen);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owners Name Array Len.");
-                cborFindResult = cbor_value_enter_container(&credMap, &owners);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owners Name.");
-                int i = 0;
-                cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
-                VERIFY_NON_NULL(TAG, cred->owners, ERROR);
-                while (cbor_value_is_valid(&owners))
+                if (cJSON_String == jsonObj->type)
                 {
-                    uint8_t *owner = NULL;
-                    cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
-                    memcpy(cred->owners[i].id, owner, len);
-                    OICFree(owner);
-                    cborFindResult = cbor_value_advance(&owners);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Owner Value.");
+                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                    cred->privateData.data = (char *)OICMalloc(jsonObjLen);
+                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
+                    strncpy((char *)cred->privateData.data, (char *)jsonObj->valuestring, jsonObjLen);
                 }
-            }
-            //PrivateData is mandatory for some of the credential types listed below.
-            if (0 == strcmp(OIC_JSON_PRIVATEDATA_NAME, name))
-            {
-                if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
-                    (cred->credType & SYMMETRIC_GROUP_KEY) ||
-                    (cred->credType & PIN_PASSWORD))
+#ifdef __WITH_X509__
+                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
                 {
-                    cborFindResult = cbor_value_dup_byte_string(&credMap,
-                        &cred->privateData.data, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Private Data Value.");
+                    cred->privateData.data = cJSON_PrintUnformatted(jsonObj);
+                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
                 }
+#endif // __WITH_X509__
             }
             else
             {
@@ -404,79 +345,102 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
             }
 
             //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
-            if (0 == strcmp(OIC_JSON_PUBLICDATA_NAME, name))
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
+#ifdef __WITH_X509__
+            if (cred->credType & SIGNED_ASYMMETRIC_KEY)
             {
-                if (cred->credType & SIGNED_ASYMMETRIC_KEY)
+                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
+            }
+#endif //  __WITH_X509__
+            if (NULL != jsonObj)
+            {
+                if (cJSON_String == jsonObj->type)
+                {
+                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                    cred->publicData.data = (char *)OICMalloc(jsonObjLen);
+                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
+                    strncpy((char *)cred->publicData.data, (char *)jsonObj->valuestring, jsonObjLen);
+                }
+#ifdef __WITH_X509__
+                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
                 {
-                    cborFindResult = cbor_value_dup_byte_string(&credMap,
-                        &cred->publicData.data, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ");
+                    cred->publicData.data = cJSON_PrintUnformatted(jsonObj);
+                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
                 }
+#endif //  __WITH_X509__
             }
+
             //Period -- Not Mandatory
-            if (0 == strcmp(OIC_JSON_PERIOD_NAME, name))
-            {
-                cborFindResult = cbor_value_dup_text_string(&credMap,
-                    &cred->period, &len, NULL);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Period Name Value.");
-            }
-            if (CborMapType != type && cbor_value_is_valid(&credMap))
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
+            if(jsonObj && cJSON_String == jsonObj->type)
             {
-                cborFindResult = cbor_value_advance(&credMap);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Map.");
+                jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                cred->period = (char *)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, cred->period, ERROR);
+                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
             }
-            OICFree(name);
-            name = NULL;
-        }
 
-        cred->next = NULL;
-        if (NULL == headCred)
-        {
-            headCred = cred;
-        }
-        else
-        {
-            OicSecCred_t *temp = headCred;
-            while (temp->next)
+            //Owners -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+            cred->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
+            cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
+            VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
+            for(size_t i = 0; i < cred->ownersLen; i++)
             {
-                temp = temp->next;
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, i);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
+                outLen = 0;
+                memset(base64Buff, 0, sizeof(base64Buff));
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring),
+                         base64Buff, sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK &&
+                               outLen <= sizeof(cred->owners[i].id)), ERROR);
+                memcpy(cred->owners[i].id, base64Buff, outLen);
             }
-            temp->next = cred;
-        }
-        if (cbor_value_is_valid(&credArray))
-        {
-            cborFindResult = cbor_value_advance(&credArray);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Array. ");
-        }
+            prevCred = cred;
+        } while( ++idx < numCred);
     }
-    *secCred = headCred;
+
     ret = OC_STACK_OK;
+
 exit:
-    if (CborNoError != cborFindResult)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
         DeleteCredList(headCred);
         headCred = NULL;
-        ret = OC_STACK_ERROR;
-    }
-    if (cred)
-    {
-        DeleteCredList(cred);
     }
-    if (name)
-    {
-        OICFree(name);
-    }
-    return ret;
+    return headCred;
 }
 
+/**
+ * This function generates the bin credential data.
+ *
+ * @param subject pointer to subject of this credential.
+ * @param credType credential type.
+ * @param publicData public data such as public key.
+ * @param privateData private data such as private key.
+ *        The privateData is expected in base64 encoded format.
+ * @param ownersLen length of owners array
+ * @param owners array of owners.
+ *
+ * @retval
+ *      pointer to instance of OicSecCred_t  - success
+ *      NULL                                 - error
+ */
 OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
-                                  const uint8_t * publicData, const uint8_t* privateData,
-                                  size_t ownersLen, const OicUuid_t * owners)
+                                 const char * publicData, const char * privateData,
+                                 size_t ownersLen, const OicUuid_t * owners)
 {
     (void)publicData;
     OCStackResult ret = OC_STACK_ERROR;
 
-    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
+    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
     VERIFY_NON_NULL(TAG, cred, ERROR);
 
     //CredId is assigned before appending new cred to the existing
@@ -491,29 +455,27 @@ OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t cr
     cred->credType = credType;
 
 #ifdef __WITH_X509__
-    if (publicData)
+    if(publicData)
     {
-        cred->publicData.data = (uint8_t *)OICCalloc(1, PUBLIC_KEY_SIZE);
+        cred->publicData.data = (char *)OICMalloc(strlen(publicData)+1);
         VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
-        memcpy(cred->publicData.data, publicData, PUBLIC_KEY_SIZE);
+        strncpy((char *)cred->publicData.data, publicData, strlen(publicData)+1);
     }
 #endif // __WITH_X509__
 
-    if (privateData)
+    if(privateData)
     {
-#ifdef __WITH_X509__
-        cred->privateData.data = (uint8_t *)OICCalloc(1, PRIVATE_KEY_SIZE);
+        cred->privateData.data = (char *)OICMalloc(strlen(privateData)+1);
         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-        memcpy(cred->privateData.data, privateData, PRIVATE_KEY_SIZE);
-#endif // __WITH_X509__
+        strncpy((char *)cred->privateData.data, privateData, strlen(privateData)+1);
     }
 
     VERIFY_SUCCESS(TAG, ownersLen > 0, ERROR);
     cred->ownersLen = ownersLen;
 
-    cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
+    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
     VERIFY_NON_NULL(TAG, cred->owners, ERROR);
-    for (size_t i = 0; i < cred->ownersLen; i++)
+    for(size_t i = 0; i < cred->ownersLen; i++)
     {
         memcpy(cred->owners[i].id, owners[i].id, sizeof(cred->owners[i].id));
     }
@@ -533,20 +495,22 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
     bool ret = false;
 
     // Convert Cred data into JSON for update to persistent storage
-    uint8_t *payload = NULL;
-    size_t size = 0;
-    OCStackResult res = CredToCBORPayload(cred, &payload, &size);
-    if ((OC_STACK_OK == res) && payload)
+    char *jsonStr = BinToCredJSON(cred);
+    if (jsonStr)
     {
-        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
+        cJSON *jsonCred = cJSON_Parse(jsonStr);
+        OICFree(jsonStr);
+
+        if ((jsonCred) &&
+          (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, jsonCred)))
         {
             ret = true;
         }
-        OICFree(payload);
+        cJSON_Delete(jsonCred );
     }
     else //Empty cred list
     {
-        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, NULL, size))
+        if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, NULL))
         {
             ret = true;
         }
@@ -555,22 +519,23 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
 }
 
 /**
- * Compare function used LL_SORT for sorting credentials.
+ * Compare function used LL_SORT for sorting credentials
  *
- * @param first pointer to OicSecCred_t struct.
- * @param second  pointer to OicSecCred_t struct.
+ * @param first   pointer to OicSecCred_t struct
+ * @param second  pointer to OicSecCred_t struct
  *
- *@return -1, if credId of first is less than credId of second.
- * 0, if credId of first is equal to credId of second.
- * 1, if credId of first is greater than credId of second.
+ *@retval
+ *  -1    if credId of first is less than credId of second
+ *   0    if credId of first is equal to credId of second
+ *   1    if credId of first is greater than credId of second
  */
 static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
 {
-    if (first->credId < second->credId)
+    if(first->credId < second->credId)
     {
         return -1;
     }
-    else if (first->credId > second->credId)
+    else if(first->credId > second->credId)
     {
         return 1;
     }
@@ -584,19 +549,23 @@ static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
  * available due deletion of OicSecCred_t object or one more than
  * credId of last credential in the list.
  *
- * @return next available credId if successful, else 0 for error.
+ * @retval
+ *      next available credId  - success
+ *      0                      - error
  */
+
 static uint16_t GetCredId()
 {
     //Sorts credential list in incremental order of credId
     LL_SORT(gCred, CmpCredId);
 
+
     OicSecCred_t *currentCred = NULL, *credTmp = NULL;
     uint16_t nextCredId = 1;
 
     LL_FOREACH_SAFE(gCred, currentCred, credTmp)
     {
-        if (currentCred->credId == nextCredId)
+        if(currentCred->credId == nextCredId)
         {
             nextCredId += 1;
         }
@@ -614,29 +583,38 @@ exit:
 }
 
 /**
- * Get the default value.
- *
- * @return  NULL for now.
+ * Get the default value
+ * @retval  NULL for now. Update it when we finalize the default info.
  */
 static OicSecCred_t* GetCredDefault()
 {
-    // TODO:Update it when we finalize the default info.
     return NULL;
 }
 
+/**
+ * This function adds the new cred to the credential list.
+ *
+ * @param cred pointer to new credential.
+ *
+ * @retval
+ *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
+ *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
+ */
 OCStackResult AddCredential(OicSecCred_t * newCred)
 {
     OCStackResult ret = OC_STACK_ERROR;
+
     VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);
 
     //Assigning credId to the newCred
     newCred->credId = GetCredId();
+
     VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
 
     //Append the new Cred to existing list
     LL_APPEND(gCred, newCred);
 
-    if (UpdatePersistentStorage(gCred))
+    if(UpdatePersistentStorage(gCred))
     {
         ret = OC_STACK_OK;
     }
@@ -654,7 +632,7 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
 
     LL_FOREACH_SAFE(gCred, cred, tempCred)
     {
-        if (memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
+        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
         {
             LL_DELETE(gCred, cred);
             FreeCred(cred);
@@ -662,9 +640,9 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
         }
     }
 
-    if (deleteFlag)
+    if(deleteFlag)
     {
-        if (UpdatePersistentStorage(gCred))
+        if(UpdatePersistentStorage(gCred))
         {
             ret = OC_STACK_RESOURCE_DELETED;
         }
@@ -685,7 +663,7 @@ OCStackResult RemoveAllCredentials(void)
     DeleteCredList(gCred);
     gCred = GetCredDefault();
 
-    if (!UpdatePersistentStorage(gCred))
+    if(!UpdatePersistentStorage(gCred))
     {
         return OC_STACK_ERROR;
     }
@@ -700,7 +678,7 @@ OCStackResult RemoveAllCredentials(void)
  * @param ownerAdd address of OBT(PT)
  * @param doxm current device's doxm resource
  *
- * @return
+ * @retval
  *     true successfully done and valid ower psk information
  *     false Invalid owner psk information or failed to owner psk generation
  */
@@ -723,17 +701,34 @@ static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoi
     OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);
 
     //Generate owner credential based on recevied credential information
-    receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
+    size_t b64BufSize = B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128 * sizeof(char));
+    uint8_t* encodeBuff = OICMalloc((b64BufSize + 1) * sizeof(char));
+    VERIFY_NON_NULL(TAG, encodeBuff, ERROR);
+    uint32_t encodedSize = 0;
+    B64Result b64Ret = b64Encode(ownerPSK, OWNER_PSK_LENGTH_128,
+                                 (char*)encodeBuff, b64BufSize + 1, &encodedSize);
+    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    encodeBuff[encodedSize] = '\0';
+
+    //memory re-allocation for private data
+    OICFree(receviedCred->privateData.data);
+    receviedCred->privateData.data = (char*)OICMalloc((encodedSize + 1) * sizeof(char));
     VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
-    memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
+
+    //fill the base64 encoded private data
+    strncpy(receviedCred->privateData.data, (char*)encodeBuff, b64BufSize + 1);
 
     OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");
 
+    //deallocate local memory
+    OICFree(encodeBuff);
+
     //Verify OwnerPSK information
     return (memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0 &&
             receviedCred->credType == SYMMETRIC_PAIR_WISE_KEY);
 exit:
     //receviedCred->privateData.data will be deallocated when deleting credential.
+    OICFree(encodeBuff);
     return false;
 }
 
@@ -744,11 +739,9 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
     //Get binary representation of json
-    OicSecCred_t * cred  = NULL;
-    uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData1);
-    //size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
-    OCStackResult res = CBORPayloadToCred(payload, 0, &cred);
-    if (res == OC_STACK_OK)
+    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if(cred)
     {
 #ifdef __WITH_DTLS__
         OicUuid_t emptyUuid = {.id={0}};
@@ -874,7 +867,7 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
 #endif//__WITH_DTLS__
     }
 
-    if (OC_EH_RESOURCE_CREATED != ret)
+    if(OC_EH_RESOURCE_CREATED != ret)
     {
         if(OC_STACK_OK != RemoveCredential(&cred->subject))
         {
@@ -890,11 +883,10 @@ static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * eh
 {
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
-    //Get binary representation of CBOR
-    OicSecCred_t *cred  = NULL;
-    uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
-    OCStackResult res = CBORPayloadToCred(payload, 0, &cred);
-    if ((OC_STACK_OK == res) && cred)
+    //Get binary representation of json
+    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if(cred)
     {
         //If the Post request credential has credId, it will be
         //discarded and the next available credId will be assigned
@@ -912,41 +904,54 @@ static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *e
 
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    if (NULL == ehRequest->query)
+    if(NULL == ehRequest->query)
    {
        return ehRet;
    }
 
-   OicParseQueryIter_t parseIter = { .attrPos=NULL };
+   OicParseQueryIter_t parseIter = {.attrPos=NULL};
    OicUuid_t subject = {.id={0}};
 
    //Parsing REST query to get the subject
    ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
-   while (GetNextQuery(&parseIter))
+   while(GetNextQuery(&parseIter))
    {
-       if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
+       if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
                parseIter.attrLen) == 0)
        {
-           memcpy(subject.id, parseIter.valPos, parseIter.valLen);
+           unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+           uint32_t outLen = 0;
+           B64Result b64Ret = B64_OK;
+
+           b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen,
+                   base64Buff, sizeof(base64Buff), &outLen);
+
+           VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
+           memcpy(subject.id, base64Buff, outLen);
        }
    }
 
-   if (OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
+   if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
    {
        ehRet = OC_EH_RESOURCE_DELETED;
    }
 
+exit:
     return ehRet;
 }
 
-OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
+/*
+ * This internal method is the entity handler for Cred resources
+ * to handle REST request (PUT/POST/DEL)
+ */
+OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
                                         OCEntityHandlerRequest * ehRequest,
                                         void* callbackParameter)
 {
     (void)callbackParameter;
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
-    if (!ehRequest)
+    if(!ehRequest)
     {
         return OC_EH_ERROR;
     }
@@ -954,7 +959,7 @@ OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
     {
         OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         //TODO :  Handle PUT/DEL methods
-        switch (ehRequest->method)
+        switch(ehRequest->method)
         {
             case OC_REST_GET:
                 ret = OC_EH_FORBIDDEN;
@@ -975,21 +980,26 @@ OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
     }
 
     //Send payload to request originator
-    ret = (SendSRMCBORResponse(ehRequest, ret, NULL) == OC_STACK_OK) ?
-                       ret : OC_EH_ERROR;
+    ret = (SendSRMResponse(ehRequest, ret, NULL) == OC_STACK_OK ?
+                       ret : OC_EH_ERROR);
 
     return ret;
 }
 
+/*
+ * This internal method is used to create '/oic/sec/Cred' resource.
+ */
 OCStackResult CreateCredResource()
 {
-    OCStackResult ret = OCCreateResource(&gCredHandle,
-                                         OIC_RSRC_TYPE_SEC_CRED,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_CRED_URI,
-                                         CredEntityHandler,
-                                         NULL,
-                                         OC_RES_PROP_NONE);
+    OCStackResult ret;
+
+    ret = OCCreateResource(&gCredHandle,
+                           OIC_RSRC_TYPE_SEC_CRED,
+                           OIC_MI_DEF,
+                           OIC_RSRC_CRED_URI,
+                           CredEntityHandler,
+                           NULL,
+                           OC_RES_PROP_NONE);
 
     if (OC_STACK_OK != ret)
     {
@@ -999,40 +1009,49 @@ OCStackResult CreateCredResource()
     return ret;
 }
 
+/**
+ * Initialize Cred resource by loading data from persistent storage.
+ *
+ * @retval
+ *     OC_STACK_OK    - no errors
+ *     OC_STACK_ERROR - stack process error
+ */
 OCStackResult InitCredResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     //Read Cred resource from PS
-    uint8_t *data = NULL;
-    size_t size = 0;
-    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_CRED_NAME, &data, &size);
-    // If database read failed
-    if (ret != OC_STACK_OK)
-    {
-        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
-    if (data)
+    char* jsonSVRDatabase = GetSVRDatabase();
+
+    if (jsonSVRDatabase)
     {
-        // Read ACL resource from PS
-        ret = CBORPayloadToCred(data, size, &gCred);
+        //Convert JSON Cred into binary format
+        gCred = JSONToCredBin(jsonSVRDatabase);
     }
-
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default Cred is created
      * which allows user to initiate Cred provisioning again.
      */
-    if (ret != OC_STACK_OK || !data || !gCred)
+    if (!jsonSVRDatabase || !gCred)
     {
         gCred = GetCredDefault();
     }
     //Instantiate 'oic.sec.cred'
     ret = CreateCredResource();
-    OICFree(data);
+    OICFree(jsonSVRDatabase);
     return ret;
 }
 
+/**
+ * Perform cleanup for Cred resources.
+ *
+ * @return
+ *     OC_STACK_OK              - no errors
+ *     OC_STACK_ERROR           - stack process error
+ *     OC_STACK_NO_RESOURCE     - resource not found
+ *     OC_STACK_INVALID_PARAM   - invalid param
+ */
 OCStackResult DeInitCredResource()
 {
     OCStackResult result = OCDeleteResource(gCredHandle);
@@ -1041,6 +1060,15 @@ OCStackResult DeInitCredResource()
     return result;
 }
 
+/**
+ * This method is used by tinydtls/SRM to retrieve credential for given Subject.
+ *
+ * @param subject - subject for which credential is required.
+ *
+ * @retval
+ *     reference to OicSecCred_t - if credential is found
+ *     NULL                      - if credential not found
+ */
 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
 {
     OicSecCred_t *cred = NULL;
@@ -1062,9 +1090,22 @@ const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
 
 
 #if defined(__WITH_DTLS__)
-int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
-              const uint8_t *desc, size_t desc_len,
-              uint8_t *result, size_t result_length)
+/**
+ * This internal callback is used by lower stack (i.e. CA layer) to
+ * retrieve PSK credentials from RI security layer.
+ *
+ * @param[in]  type type of PSK data required by tinyDTLS layer during DTLS handshake.
+ * @param[in]  desc Additional request information.
+ * @param[in]  desc_len The actual length of desc.
+ * @param[out] result  Must be filled with the requested information.
+ * @param[in]  result_length  Maximum size of @p result.
+ *
+ * @return The number of bytes written to @p result or a value
+ *         less than zero on error.
+ */
+int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
+              const unsigned char *desc, size_t desc_len,
+              unsigned char *result, size_t result_length)
 {
     int32_t ret = -1;
 
@@ -1123,10 +1164,18 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
                             }
                         }
 
-                        // Copy PSK.
-                        result_length = sizeof(cred->privateData.data);
-                        memcpy(result, cred->privateData.data, result_length);
-                        return result_length;
+                        // Convert PSK from Base64 encoding to binary before copying
+                        uint32_t outLen = 0;
+                        B64Result b64Ret = b64Decode(cred->privateData.data,
+                                strlen(cred->privateData.data), result,
+                                result_length, &outLen);
+                        if (B64_OK != b64Ret)
+                        {
+                            OIC_LOG (ERROR, TAG, "Base64 decoding failed.");
+                            ret = -1;
+                            return ret;
+                        }
+                        return outLen;
                     }
                 }
             }
@@ -1168,14 +1217,19 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
     }
 
     uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
-    OicSecCred_t* cred = NULL;
     int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, owners->id,
                                               UUID_LENGTH, PBKDF_ITERATIONS,
                                               OWNER_PSK_LENGTH_128, privData);
     VERIFY_SUCCESS(TAG, (0 == dtlsRes) , ERROR);
 
-    cred = GenerateCredential(tmpSubject, credType, NULL,
-                              privData, ownersLen, owners);
+    uint32_t outLen = 0;
+    char base64Buff[B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128) + 1] = {};
+    B64Result b64Ret = b64Encode(privData, OWNER_PSK_LENGTH_128, base64Buff,
+                                sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, (B64_OK == b64Ret), ERROR);
+
+    OicSecCred_t* cred = GenerateCredential(tmpSubject, credType, NULL,
+                                            base64Buff, ownersLen, owners);
     if(NULL == cred)
     {
         OIC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to generate credential");
@@ -1204,6 +1258,7 @@ exit:
 #define CERTIFICATE ("x5c")
 #define PRIVATE_KEY ("d")
 
+
 static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen)
 {
     for (size_t i = 0; i < CERT_LEN_PREFIX; ++i)
@@ -1215,9 +1270,9 @@ static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen)
 static uint32_t ParseCertPrefix(uint8_t *prefix)
 {
     uint32_t res = 0;
-    if (NULL != prefix)
+    if(NULL != prefix)
     {
-        for (int i = 0; i < CERT_LEN_PREFIX; ++i)
+        for(int i=0; i < CERT_LEN_PREFIX; ++i)
         {
             res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE));
         }
@@ -1225,30 +1280,34 @@ static uint32_t ParseCertPrefix(uint8_t *prefix)
     return res;
 }
 
-static uint32_t appendCert2Chain(uint8_t *appendPoint, uint8_t *cert, size_t len, uint32_t max_len)
+static uint32_t appendCert2Chain(uint8_t *appendPoint, char *cert, uint32_t max_len)
 {
     uint32_t ret = 0;
     VERIFY_NON_NULL(TAG, appendPoint, ERROR);
     VERIFY_NON_NULL(TAG, cert, ERROR);
 
-    memcpy(appendPoint + CERT_LEN_PREFIX, cert, max_len - CERT_LEN_PREFIX);
-    WriteCertPrefix(appendPoint, len);
+    uint32_t certLen;
+    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(cert, strlen(cert), appendPoint + CERT_LEN_PREFIX,
+                                            max_len - CERT_LEN_PREFIX, &certLen), ERROR);
+    WriteCertPrefix(appendPoint, certLen);
 
-    ret = len + CERT_LEN_PREFIX;
+    ret = certLen + CERT_LEN_PREFIX;
 exit:
     return ret;
 }
 
-static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo)
-{
+static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo){
     OCStackResult ret = OC_STACK_ERROR;
     uint8_t *ccPtr = credInfo->certificateChain;
-    for (uint8_t i = 0; i < credInfo->chainLen - 1; ++i)
+    for(uint32_t i =0; i < credInfo->chainLen - 1; ++i)
     {
         ccPtr += CERT_LEN_PREFIX + ParseCertPrefix(ccPtr);
     }
 
-    ByteArray cert = { .data = ccPtr + CERT_LEN_PREFIX, .len = ParseCertPrefix(ccPtr) };
+    ByteArray cert = {
+        .data = ccPtr + CERT_LEN_PREFIX,
+        .len = ParseCertPrefix(ccPtr)
+         };
     CertificateX509 certStruct;
 
     VERIFY_SUCCESS(TAG, PKI_SUCCESS == DecodeCertificate(cert, &certStruct), ERROR);
@@ -1263,6 +1322,70 @@ static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo)
     return ret;
 }
 
+static OCStackResult GetCertCredPublicData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    cJSON *jsonRoot = NULL;
+
+    VERIFY_NON_NULL(TAG, credInfo, ERROR);
+    VERIFY_NON_NULL(TAG, cred, ERROR);
+    VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
+    //VERIFY_SUCCESS(TAG, NULL == credInfo->certificateChain.data, ERROR);
+    jsonRoot = cJSON_Parse(cred->publicData.data);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    //Get certificate chain
+    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, CERTIFICATE);//TODO define field names constants
+    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_Array == jsonObj->type, ERROR);
+
+    size_t certChainLen = (size_t)cJSON_GetArraySize(jsonObj);
+    credInfo->chainLen = certChainLen;
+    VERIFY_SUCCESS(TAG, MAX_CHAIN_LEN >= certChainLen, ERROR);
+
+    uint32_t len = 0;
+    for (size_t i = 0; i < certChainLen; ++i)
+    {
+        cJSON *item = cJSON_GetArrayItem(jsonObj, i);
+        VERIFY_NON_NULL(TAG, item, ERROR);
+        VERIFY_SUCCESS(TAG, cJSON_String == item->type, ERROR);
+        uint32_t appendedLen = appendCert2Chain(credInfo->certificateChain + len, item->valuestring,
+                                              MAX_CERT_MESSAGE_LEN - len);
+        VERIFY_SUCCESS(TAG, 0 != appendedLen, ERROR);
+        len += appendedLen;
+    }
+    credInfo->certificateChainLen = len;
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCAPublicKeyData(credInfo), ERROR);
+    ret = OC_STACK_OK;
+exit:
+    cJSON_Delete(jsonRoot);
+    return ret;
+}
+
+static OCStackResult GetCertCredPrivateData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    cJSON *jsonRoot = NULL;
+    VERIFY_NON_NULL(TAG, credInfo, ERROR);
+    VERIFY_NON_NULL(TAG, cred, ERROR);
+    VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
+    jsonRoot = cJSON_Parse(cred->privateData.data);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, PRIVATE_KEY);//TODO define field names constants
+    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_String == jsonObj->type, ERROR);
+
+    uint32_t read = 0u;
+    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
+                                            credInfo->devicePrivateKey, PRIVATE_KEY_SIZE, &read)
+                   && PRIVATE_KEY_SIZE == read, ERROR);
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    return ret;
+}
+
 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
 {
     int ret = 1;
@@ -1276,41 +1399,8 @@ int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
     LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY);
     VERIFY_NON_NULL(TAG, cred, ERROR);
 
-    CborValue credCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    uint8_t *cborPayload = cred->publicData.data;
-    int cborLen = cred->publicData.len;
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &credCbor);
-    CborValue certMap;
-    cborFindResult = cbor_value_enter_container(&credCbor, &certMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Map.");
-
-    CborValue certs;
-    cborFindResult = cbor_value_map_find_value(&certs, CERTIFICATE, &certs);
-    if (cbor_value_is_array(&certs))
-    {
-        cborFindResult = cbor_value_get_array_length(&certs, (size_t *)&credInfo->chainLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Chain Len.");
-        CborValue cert;
-        cborFindResult = cbor_value_enter_container(&certs, &cert);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Container.");
-        size_t len = 0;
-        size_t certLen = 0;
-        uint8_t *val = NULL;
-        while (cbor_value_is_byte_string(&cert))
-        {
-            cborFindResult = cbor_value_dup_byte_string(&cert, &val, &certLen, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Value.");
-            cborFindResult = cbor_value_advance(&cert);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a Period Array.");
-            uint32_t appendedLen = appendCert2Chain(credInfo->certificateChain + len, val, certLen, MAX_CERT_MESSAGE_LEN - len);
-            len += appendedLen;
-        }
-        credInfo->certificateChainLen = len;
-        GetCAPublicKeyData(credInfo);
-    }
-    memcpy(credInfo->devicePrivateKey, cred->privateData.data, PRIVATE_KEY_SIZE);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPrivateData(credInfo, cred), ERROR);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPublicData(credInfo, cred), ERROR);
 
     ret = 0;
 exit:
index e30c07d..9255508 100644 (file)
@@ -314,13 +314,13 @@ static OCEntityHandlerResult HandleCRLPostRequest(const OCEntityHandlerRequest *
 }
 
 
-/**
+/*
  * This internal method is the entity handler for CRL resource and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-static OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
-                                              OCEntityHandlerRequest *ehRequest,
-                                              void *callbackParameter)
+OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
+                                       OCEntityHandlerRequest *ehRequest,
+                                       void *callbackParameter)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     (void)callbackParameter;
@@ -356,18 +356,19 @@ static OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
     return ehRet;
 }
 
-/**
+/*
  * This internal method is used to create '/oic/sec/crl' resource.
  */
-static OCStackResult CreateCRLResource()
+OCStackResult CreateCRLResource()
 {
-    OCStackResult ret = OCCreateResource(&gCrlHandle,
-                                         OIC_RSRC_TYPE_SEC_CRL,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_CRL_URI,
-                                         CRLEntityHandler,
-                                         NULL,
-                                         OC_OBSERVABLE);
+    OCStackResult ret;
+    ret = OCCreateResource(&gCrlHandle,
+                           OIC_RSRC_TYPE_SEC_CRL,
+                           OIC_MI_DEF,
+                           OIC_RSRC_CRL_URI,
+                           CRLEntityHandler,
+                           NULL,
+                           OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
@@ -378,8 +379,8 @@ static OCStackResult CreateCRLResource()
 }
 
 /**
- * Get the default value.
- * @return defaultCrl for now.
+ * Get the default value
+ * @retval  NULL for now. Update it when we finalize the default info.
  */
 static OicSecCrl_t *GetCrlDefault()
 {
index 6750a62..0690724 100644 (file)
@@ -826,7 +826,7 @@ static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHan
     (void)UNUSED;\r
     if (clientResponse)\r
     {\r
-        OIC_LOG_V(INFO, TAG, "StackResult: %s", clientResponse->result);\r
+        OIC_LOG_V(INFO, TAG, "StackResult: %d", clientResponse->result);\r
         OIC_LOG_V(INFO, TAG,\r
                 "Device =============> Discovered @ %s:%d",\r
                 clientResponse->devAddr.addr,\r
@@ -865,7 +865,6 @@ static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHan
                 return OC_STACK_KEEP_TRANSACTION;\r
             }\r
 \r
-\r
             char rsrc_uri[MAX_URI_LENGTH+1] = {0};\r
             int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",\r
                       OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DPAIRING);\r
index 49adaf9..860a78d 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include <stdlib.h>
-#include <string.h>
-
-#if HAVE_STRINGS_H
-#include <strings.h>
-#endif
-
-#ifdef __WITH_DTLS__
-#include "global.h"
-#endif
 
 #include "ocstack.h"
+#include "logger.h"
 #include "oic_malloc.h"
-#include "payload_logging.h"
-#include "utlist.h"
-#include "ocrandom.h"
-#include "ocpayload.h"
-#include "cainterface.h"
-#include "ocserverrequest.h"
+#include "cJSON.h"
 #include "resourcemanager.h"
 #include "doxmresource.h"
 #include "pstatresource.h"
 #include "aclresource.h"
 #include "psinterface.h"
+#include "utlist.h"
 #include "srmresourcestrings.h"
 #include "securevirtualresourcetypes.h"
+#include "base64.h"
+#include "ocrandom.h"
+#include "cainterface.h"
 #include "credresource.h"
+#include "ocserverrequest.h"
 #include "srmutility.h"
 #include "pinoxmcommon.h"
 
-#define TAG  "SRM-DOXM"
+#ifdef __WITH_DTLS__
+#include "global.h"
+#endif
 
-/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
- * The value of payload size is increased until reaching belox max cbor size. */
-static const uint8_t CBOR_SIZE = 255;
+#include <stdlib.h>
+#include <string.h>
 
-/** Max cbor size payload. */
-static const uint16_t CBOR_MAX_SIZE = 4400;
+#if HAVE_STRINGS_H
+#include <strings.h>
+#endif
 
-/** DOXM Map size - Number of mandatory items. */
-static const uint8_t DOXM_MAP_SIZE = 5;
+#define TAG  "SRM-DOXM"
 
 static OicSecDoxm_t        *gDoxm = NULL;
 static OCResourceHandle    gDoxmHandle = NULL;
@@ -96,106 +88,58 @@ void DeleteDoxmBinData(OicSecDoxm_t* doxm)
     }
 }
 
-OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size)
+char * BinToDoxmJSON(const OicSecDoxm_t * doxm)
 {
-    if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
+    if (NULL == doxm)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
-    size_t cborLen = *size;
-    if (0 == cborLen)
-    {
-        cborLen = CBOR_SIZE;
-    }
-
-    *payload = NULL;
-    *size = 0;
-
-    OCStackResult ret = OC_STACK_ERROR;
-
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder doxmMap = { {.ptr = NULL }, .end = 0 };
+    char *jsonStr = NULL;
+    cJSON *jsonDoxm = NULL;
+    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+    uint32_t outLen = 0;
+    B64Result b64Ret = B64_OK;
 
-    CborError cborEncoderResult = CborNoError;
+    cJSON *jsonRoot = cJSON_CreateObject();
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    uint8_t mapSize = DOXM_MAP_SIZE;
-
-    if (doxm->oxmTypeLen > 0)
-    {
-        mapSize++;
-    }
-    if (doxm->oxmLen > 0)
-    {
-        mapSize++;
-    }
-
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
-
-    cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
+    jsonDoxm = cJSON_CreateObject();
+    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
+    cJSON_AddItemToObject(jsonRoot, OIC_JSON_DOXM_NAME, jsonDoxm );
 
     //OxmType -- Not Mandatory
-    if (doxm->oxmTypeLen > 0)
+    if(doxm->oxmTypeLen > 0)
     {
-        cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
-            strlen(OIC_JSON_OXM_TYPE_NAME));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
-        CborEncoder oxmType = { {.ptr = NULL }, .end = 0 };
-        cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
-
+        cJSON *jsonOxmTyArray = cJSON_CreateArray();
+        VERIFY_NON_NULL(TAG, jsonOxmTyArray, ERROR);
+        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_TYPE_NAME, jsonOxmTyArray );
         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
         {
-            cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
-                strlen(doxm->oxmType[i]));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
+            cJSON_AddItemToArray (jsonOxmTyArray, cJSON_CreateString(doxm->oxmType[i]));
         }
-        cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
     }
 
     //Oxm -- Not Mandatory
-    if (doxm->oxmLen > 0)
+    if(doxm->oxmLen > 0)
     {
-        cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_NAME,
-            strlen(OIC_JSON_OXM_NAME));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
-        CborEncoder oxm = { {.ptr = NULL }, .end = 0 };
-        cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
-
+        cJSON *jsonOxmArray = cJSON_CreateArray();
+        VERIFY_NON_NULL(TAG, jsonOxmArray, ERROR);
+        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_NAME,jsonOxmArray );
         for (size_t i = 0; i < doxm->oxmLen; i++)
         {
-            cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
+            cJSON_AddItemToArray (jsonOxmArray, cJSON_CreateNumber(doxm->oxm[i]));
         }
-        cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
     }
 
     //OxmSel -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
-        strlen(OIC_JSON_OXM_SEL_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
-    cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
+    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_OXM_SEL_NAME, (int)doxm->oxmSel);
 
     //sct -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
-        strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
-    cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
+    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, (int)doxm->sct);
 
     //Owned -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
-        strlen(OIC_JSON_OWNED_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
-    cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
+    cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_OWNED_NAME, doxm->owned);
 
     //TODO: Need more clarification on deviceIDFormat field type.
 #if 0
@@ -204,209 +148,209 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, siz
 #endif
 
     //DeviceId -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
-        strlen(OIC_JSON_DEVICE_ID_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
-    cborEncoderResult = cbor_encode_byte_string(&doxmMap, doxm->deviceID.id,
-                                                sizeof(doxm->deviceID.id));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
+    outLen = 0;
+    b64Ret = b64Encode(doxm->deviceID.id, sizeof(doxm->deviceID.id), base64Buff,
+                    sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_DEVICE_ID_NAME, base64Buff);
 
     //DPC -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
-        strlen(OIC_JSON_DPC_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
-    cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
+    cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_DPC_NAME, doxm->dpc);
 
     //Owner -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNER_NAME,
-        strlen(OIC_JSON_OWNER_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner tag.");
-    cborEncoderResult = cbor_encode_byte_string(&doxmMap, doxm->owner.id,
-                                                sizeof(doxm->owner.id));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Value");
-
-    cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
-
-    *size = encoder.ptr - outPayload;
-    *payload = outPayload;
-    ret = OC_STACK_OK;
+    outLen = 0;
+    b64Ret = b64Encode(doxm->owner.id, sizeof(doxm->owner.id), base64Buff,
+                    sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_OWNER_NAME, base64Buff);
 
-exit:
-    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
-    {
-       // reallocate and try again!
-       OICFree(outPayload);
-       // Since the allocated initial memory failed, double the memory.
-       cborLen += encoder.ptr - encoder.end;
-       cborEncoderResult = CborNoError;
-       ret = DoxmToCBORPayload(doxm, payload, &cborLen);
-    }
+    jsonStr = cJSON_PrintUnformatted(jsonRoot);
 
-    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+exit:
+    if (jsonRoot)
     {
-       OICFree(outPayload);
-       outPayload = NULL;
-       *payload = NULL;
-       *size = 0;
-       ret = OC_STACK_ERROR;
+        cJSON_Delete(jsonRoot);
     }
-
-    return ret;
+    return jsonStr;
 }
 
-OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
-                                OicSecDoxm_t **secDoxm)
+OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
 {
-    if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm)
+
+    if (NULL == jsonStr)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
-    *secDoxm = NULL;
+    OicSecDoxm_t *doxm =  NULL;
+    cJSON *jsonDoxm = NULL;
+    cJSON *jsonObj = NULL;
 
-    CborValue doxmCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    int cborLen = size;
-    if (0 == size)
-    {
-        cborLen = CBOR_SIZE;
-    }
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &doxmCbor);
-    CborValue doxmMap = { .parser = NULL } ;
-    OicSecDoxm_t *doxm = NULL;
-    cborFindResult = cbor_value_enter_container(&doxmCbor, &doxmMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Doxm Map.")
+    size_t jsonObjLen = 0;
+    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+    uint32_t outLen = 0;
+    B64Result b64Ret = B64_OK;
 
-    doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
+    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
+
+    doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
     VERIFY_NON_NULL(TAG, doxm, ERROR);
 
-    while (cbor_value_is_valid(&doxmMap))
+    //OxmType -- not Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
+    if ((jsonObj) && (cJSON_Array == jsonObj->type))
     {