PeterO.Cbor 5.0.0-alpha1

This is a prerelease version of PeterO.Cbor.
dotnet add package PeterO.Cbor --version 5.0.0-alpha1                
NuGet\Install-Package PeterO.Cbor -Version 5.0.0-alpha1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PeterO.Cbor" Version="5.0.0-alpha1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PeterO.Cbor --version 5.0.0-alpha1                
#r "nuget: PeterO.Cbor, 5.0.0-alpha1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install PeterO.Cbor as a Cake Addin
#addin nuget:?package=PeterO.Cbor&version=5.0.0-alpha1&prerelease

// Install PeterO.Cbor as a Cake Tool
#tool nuget:?package=PeterO.Cbor&version=5.0.0-alpha1&prerelease                

CBOR

NuGet Status

Download source code: ZIP file


A C# implementation of Concise Binary Object Representation, a general-purpose binary data format defined in RFC 8949. According to that RFC, CBOR's data model "is an extended version of the JSON data model", supporting many more types of data than JSON. "CBOR was inspired by MessagePack", but "is not intended as a version of or replacement for MessagePack."

This implementation was written by Peter O. and is released to the Public Domain under the CC0 Declaration.

This implementation also doubles as a reader and writer of JSON, and can convert data from JSON to CBOR and back.

Finally, this implementation supports arbitrary-precision binary and decimal floating-point numbers and rational numbers with arbitrary-precision components.

Source code is available in the project page.

Note that after version 4.5x, the CBOR library's repository will stop including special projects for .NET 2.0 and .NET 4.0, leaving the .NET-Standard project for building the library.

How to Install

Starting with version 0.21.0, the C# implementation is available in the NuGet Package Gallery under the name PeterO.Cbor. To install this library as a NuGet package, enter Install-Package PeterO.Cbor in the NuGet Package Manager Console.

Documentation

This library defines one class, called CBORObject, that allows you to read and write CBOR objects to and from data streams and byte arrays, and to convert JSON text to CBOR objects and back.

See the C# (.NET) API documentation.

The C# implementation is designed as a Portable Class Library.

Other Sites

Examples

The following shows certain use examples of this library. Additional examples can be found in the API documentation.

Creating a map and converting that map to CBOR bytes and a JSON string:

// The following creates a CBOR map and adds
// several kinds of objects to it
var cbor = CBORObject.NewMap()
   .Add("item", "any string")
   .Add("number", 42)
   .Add("map", CBORObject.NewMap().Add("number", 42))
   .Add("array", CBORObject.NewArray().Add(999f).Add("xyz"))
   .Add("bytes", new byte[] { 0, 1, 2 });
// The following converts the map to CBOR
byte[] bytes = cbor.EncodeToBytes();
// The following converts the map to JSON
string json = cbor.ToJSONString();
Console.WriteLine(json);

Creating a map and converting that map to canonical CBOR bytes (for WebAuthn and other purposes) and a .NET dictionary:

// The following creates a CBOR map and adds
// several kinds of objects to it
var cbor = CBORObject.NewMap()
   .Add("item", "any string")
   .Add("foo", "another string")
   .Add("quux", "a third string");
// The following converts the map to canonical CBOR
byte[] bytes = cbor.EncodeToBytes(CBOREncodeOptions.DefaultCtap2Canonical);
// The following converts the map to a dictionary
var dict = cbor.ToObject<IDictionary<string,string>>();
Console.WriteLine(dict.Count);

Reading data from a file (C#). Note that all the examples for reading and writing to files assume that the platform supports file I/O; the portable class library doesn't make that assumption.

 // Read all the bytes from a file and decode the CBOR object
 // from it.  However, there are two disadvantages to this approach:
 // 1.  The byte array might be very huge, so a lot of memory to store
 // the array may be needed.
 // 2.  The decoding will succeed only if the entire array,
 // not just the start of the array, consists of a CBOR object.
 var cbor = CBORObject.DecodeFromBytes(
    File.ReadAllBytes("object.cbor"), CBOREncodeOptions.Default);

Another example of reading data from a file:

 // C#
 // Open the file stream
 using (var stream = new FileStream("object.cbor", FileMode.Open)) {
    // Read the CBOR object from the stream
    var cbor = CBORObject.Read(stream);
    // At this point, the object is read, but the file stream might
    // not have ended yet.  Here, the code may choose to read another
    // CBOR object, check for the end of the stream, or just ignore the
    // rest of the file.  The following is an example of checking for the
    // end of the stream.
    if (stream.Position != stream.Length) {
      // The end of the stream wasn't reached yet.
    } else {
      // The end of the stream was reached.
    }
 }

If a byte array contains multiple CBOR objects, the byte array should be wrapped in a MemoryStream and the stream used to read the objects, as DecodeFromBytes assumes the array contains only one CBOR object. Here is an example.

 // C#
 // Create a memory stream with a view of the byte array
 using (var stream = new MemoryStream(byteArray)) {
    // Read the CBOR object from the stream
    var cbor = CBORObject.Read(stream);
    // The rest of the example follows the one given above.
 }

Writing CBOR data to a file (C#):

// This example assumes that the variable "cbor" refers
// to a CBORObject object.
using (var stream = new FileStream("object.cbor", FileMode.Create)) {
   cbor.WriteTo(stream);
}

Writing multiple objects to a file, including arbitrary objects (the resulting file is also called a CBOR sequence):

// C#
// This example writes a sequence of objects in CBOR
// format to the same file.
using (var stream = new FileStream("object.cborseq", FileMode.Create)) {
   CBORObject.Write(true, stream);
   CBORObject.Write(422.5, stream);
   CBORObject.Write("some string", stream);
   CBORObject.Write(CBORObject.Undefined, stream);
   CBORObject.NewArray().Add(42).WriteTo(stream);
}

Reading JSON from a file:

 // Open the file stream
 using (var stream = new FileStream("object.json", FileMode.Open)) {
    // Read the JSON object from the stream
    // as a CBOR object
    var cbor = CBORObject.ReadJSON(stream);
 }

Writing a CBOR object as JSON:

// This example assumes that the variable "cbor" refers
// to a CBORObject object.
// NOTE: Specifying Encoding.UTF8 as the third parameter
// would add a byte order mark to the beginning of the text,
// but conforming JSON implementations are forbidden from
// adding it this way in JSON texts they generate.
File.WriteAllText(
  "object.json",
  cbor.ToJSONString(),
  new System.Text.Encoding.UTF8Encoding(false));

// This is an alternative way to write the CBOR object
// and is supported since version 1.2.
using (var stream = new FileStream("object2.json", FileMode.Create)) {
    // Write the CBOR object as JSON; here, a byte order
    // mark won't be added
    cbor.WriteJSONTo(stream);
}
// Version 1.2 and later support a third way to write
// objects to JSON: the CBORObject.WriteJSON method
using (var stream = new FileStream("object3.json", FileMode.Create)) {
   CBORObject.WriteJSON("some string", stream);
}
using (var stream = new FileStream("object4.json", FileMode.Create)) {
   CBORObject.WriteJSON(cbor, stream);
}
using (var stream = new FileStream("object5.json", FileMode.Create)) {
   CBORObject.WriteJSON(true, stream);
}
using (var stream = new FileStream("object6.json", FileMode.Create)) {
   CBORObject.WriteJSON(42, stream);
}

There are several ways to check whether a CBOR object is a 32-bit integer. Which one to use depends on the application's needs. Some of them follow (written in C#).

/* Accept any untagged CBOR integer
  that can fit the Int32 range */
if(!cbor.IsTagged && cbor.Type==CBORType.Integer &&
   cbor.CanValueFitInInt32()) {
  return cbor.AsInt32();
}
/* Accept any CBOR integer, tagged or not, that
 can fit the Int32 range */
if(cbor.Type==CBORType.Integer && cbor.CanValueFitInInt32()) {
  return cbor.AsInt32();
}
/* Accept any CBOR integer or floating-point number,
 tagged or not, that is an integer within the Int32 range */
if((cbor.Type==CBORType.Integer || cborType==CBORType.FloatingPoint) ||
   cbor.Untag().AsNumber().CanValueFitInInt32()) {
  return cbor.AsInt32();
}
/* Accept any CBOR object representing an integer number
   that can fit the Int32 range */
if(cbor.IsNumber && cbor.AsNumber().CanValueFitInInt32()) {
  return cbor.AsInt32();
}

The following example illustrates a custom strategy for converting objects of a given class into CBOR objects.

    public class CPOD3 {
       public string Aa { get; set; }
       public string Bb { get; set; }
       public string Cc { get; set; }
    }

    private class CPOD3Converter : ICBORToFromConverter<CPOD3> {
       public CBORObject ToCBORObject(CPOD3 cpod) {
          return CBORObject.NewMap()
             .Add(0,cpod.Aa)
             .Add(1,cpod.Bb)
             .Add(2,cpod.Cc);
       }
       public CPOD3 FromCBORObject(CBORObject obj) {
          if (obj.Type!=CBORType.Map) {
             throw new CBORException();
          }
          var ret=new CPOD3();
          ret.Aa=obj[0].AsString();
          ret.Bb=obj[1].AsString();
          ret.Cc=obj[2].AsString();
          return ret;
       }
    }

    //////////
    //  And in the code...

       var cp2=new CPOD3();
       cp2.Aa="AA";
       cp2.Bb="BB";
       cp2.Cc="CC";
       var conv=new CPOD3Converter();
       // Serialize CBOR object, passing the type mapper
       var cbor=conv.ToCBORObject(cp2);
       // Deserialize CBOR object, passing the type mapper
       cp2=conv.FromCBORObject(cbor);

NOTE: All code samples in this section are released to the Public Domain, as explained in https://creativecommons.org/publicdomain/zero/1.0/.

Demo

Go to https://github.com/peteroupc/Calculator for source code to a demo of the CBOR library in the form of a calculator.

About

Written in 2013-2019 by Peter O.

Any copyright to this work is released to the Public Domain. In case this is not possible, this work is also licensed under Creative Commons Zero (CC0): https://creativecommons.org/publicdomain/zero/1.0/

Release Notes

See History.md for release notes.

Specifications

Here are specifications by this implementation's author on certain CBOR tags:

Acknowledgments

  • Carsten Bormann reviewed this library and gave helpful suggestions.
  • Anders Gustafsson converted this library to a Portable Class Library.

I thank all users who sent issues to this repository.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp1.0 was computed.  netcoreapp1.1 was computed.  netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard1.0 is compatible.  netstandard1.1 was computed.  netstandard1.2 was computed.  netstandard1.3 was computed.  netstandard1.4 was computed.  netstandard1.5 was computed.  netstandard1.6 was computed.  netstandard2.0 was computed.  netstandard2.1 was computed. 
.NET Framework net45 was computed.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen30 was computed.  tizen40 was computed.  tizen60 was computed. 
Universal Windows Platform uap was computed.  uap10.0 was computed. 
Windows Phone wp8 was computed.  wp81 was computed.  wpa81 was computed. 
Windows Store netcore was computed.  netcore45 was computed.  netcore451 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (31)

Showing the top 5 NuGet packages that depend on PeterO.Cbor:

Package Downloads
AWSSDK.DAX.Client

AWS DynamoDB Accelerator (DAX) .NET Client -- DAX is a fully managed, in-memory cache for DynamoDB.

PubnubPCL

PubNub is a Massively Scalable Web Push Service for Web and Mobile Games. This is a cloud-based service for broadcasting messages to thousands of web and mobile clients simultaneously

Pubnub

PubNub is a Massively Scalable Web Push Service for Web and Mobile Games. This is a cloud-based service for broadcasting messages to thousands of web and mobile clients simultaneously

Com.AugustCellars.COSE

An implementation of the CBOR Object Signing and Encryption standards.

DSInternals.Common

This package is shared between all other DSInternals packages. Its main features are Azure AD Graph API and ADSI clients for for retrieval of cryptographic material. It contains implementations of common hash functions used by Windows, including NT hash, LM hash and OrgId hash. It also contains methods for SysKey/BootKey retrieval.

GitHub repositories (5)

Showing the top 5 popular GitHub repositories that depend on PeterO.Cbor:

Repository Stars
MichaelGrafnetter/DSInternals
Directory Services Internals (DSInternals) PowerShell Module and Framework
lithnet/ad-password-protection
Active Directory password filter featuring breached password checking and custom complexity rules
CICADA8-Research/RemoteKrbRelay
Remote Kerberos Relay made easy! Advanced Kerberos Relay Framework
richardschneider/net-ipfs-engine
IPFS Core API implementation in .Net
pubnub/c-sharp
PubNub clients for C-Sharp based languages, including MS Windows C#/.net, Silveright, IIS, and Mono
Version Downloads Last updated
5.0.0-alpha1 39,733 12/14/2023
4.5.3 292,310 12/13/2023
4.5.2 843,369 1/18/2022
4.5.1 29,900 1/17/2022
4.5.0 7,585 12/9/2021
4.4.4 89,772 7/1/2021
4.4.2 17,116 5/13/2021
4.4.1 4,767 4/27/2021
4.4.0 11,178 4/19/2021
4.3.0 61,524 12/7/2020
4.2.0 79,294 7/18/2020
4.1.3 391,349 5/27/2020
4.1.2 17,640 4/25/2020
4.1.1 2,341 4/15/2020
4.1.0 115,495 12/15/2019
4.0.0 77,200 9/3/2019
3.5.2 20,974 7/4/2019
3.5.1 2,898 7/1/2019
3.5.0 9,152 6/2/2019
3.4.0-beta1 1,669 10/1/2018
3.3.0 13,925 9/3/2018
3.2.0 2,144 7/30/2018

Version 5.0:

- Alpha version
- Some deprecated features from earlier versions were obsoleted.
- Attempt to make the library trimmable by making use of reflection optional.

Version 4.5:

- Add support for JSON Pointers and JSON Patches
- Add option to keep map key order when decoding CBOR and JSON
- Add option to write JSON using only ASCII characters
- CBORObject.ToString renders strings as ASCII
- Add support for deserializing CBOR objects to IReadOnlyList, IReadOnlyCollection, and ReadOnlyDictionary

Note that after version 4.5x, the CBOR library's repository will stop including special projects for .NET 2.0 and .NET 4.0, leaving the .NET-Standard project for building the library.