Java Code Examples for co.nstant.in.cbor.model.DataItem

The following examples show how to use co.nstant.in.cbor.model.DataItem. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: cbor-java   Author: c-rack   File: EncoderDecoderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTagging() throws CborException {
    UnsignedInteger a = new UnsignedInteger(1);
    NegativeInteger x = new NegativeInteger(-2);

    a.setTag(1);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    CborEncoder encoder = new CborEncoder(byteArrayOutputStream);
    encoder.encode(a);
    encoder.encode(x);
    byte[] bytes = byteArrayOutputStream.toByteArray();
    DataItem object = CborDecoder.decode(bytes).get(0);
    Assert.assertEquals(a, object);
    Assert.assertTrue(object.hasTag());
    Assert.assertEquals(1L, object.getTag().getValue());
}
 
Example #2
Source Project: amazon-freertos-ble-android-sdk   Author: aws   File: Unsubscribe.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] encode() {
    byte[] unsubscribeBytes = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ArrayBuilder<MapBuilder<CborBuilder>> topicsArray = new CborBuilder()
                .addMap()
                .put(TYPE_KEY, type)
                .putArray(TOPICS_KEY);

        for (String topic : topics) {
            topicsArray = topicsArray.add(topic);
        }

        List<DataItem> cbordata = topicsArray.end().end().build();
        new CborEncoder(baos).encode(cbordata);
        unsubscribeBytes = baos.toByteArray();
    } catch (CborException e) {
        Log.e(TAG, "Failed to encode.", e);
    }
    return unsubscribeBytes;
}
 
Example #3
Source Project: webauthndemo   Author: google   File: AuthenticatorData.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse Attestation extensions
 * 
 * @return extension map
 */
private HashMap<String, AttestationExtension> parseExtensions(byte[] extensions) {
  HashMap<String, AttestationExtension> extensionMap = new HashMap<>();

  try {
    List<DataItem> dataItems = CborDecoder.decode(extensions);

    if (dataItems.size() < 1 || !(dataItems.get(0) instanceof Map)) {
      return extensionMap;
    }
    Map map = (Map) dataItems.get(0);

    for (DataItem data : map.getKeys()) {
      if (data instanceof UnicodeString) {
        if (((UnicodeString) data).getString().equals(CableRegistrationData.KEY)) {
          CableRegistrationData decodedCableData = CableRegistrationData.parseFromCbor(map.get(data));
          extensionMap.put(CableRegistrationData.KEY, decodedCableData);
        }
      }
    }
  } catch (CborException e) {
    e.printStackTrace();
  }
  return extensionMap;
}
 
Example #4
Source Project: webauthndemo   Author: google   File: PackedAttestationStatement.java    License: Apache License 2.0 6 votes vote down vote up
@Override
DataItem encode() throws CborException {
  Map result = new Map();
  if (attestnCert != null) {
    Array x5c = new Array();
    x5c.add(new ByteString(attestnCert));
    for (byte[] cert : this.caCert) {
      x5c.add(new ByteString(cert));
    }
    result.put(new UnicodeString("x5c"), x5c);
  }
  if (ecdaaKeyId != null) {
    result.put(new UnicodeString("ecdaaKeyId"), new ByteString(ecdaaKeyId));
  }
  result.put(new UnicodeString("sig"), new ByteString(sig));
  result.put(new UnicodeString("alg"), new UnicodeString(alg.toString()));

  return result;
}
 
Example #5
Source Project: cbor-java   Author: c-rack   File: MapBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void startMapInMap() {
    CborBuilder builder = new CborBuilder();
    List<DataItem> dataItems = builder.addMap().startMap(new ByteString(new byte[] { 0x01 })).put(1, 2).end()
        .startMap(1).end().startMap("asdf").end().end().build();
    Map rootMap = (Map) dataItems.get(0);
    DataItem keys[] = new DataItem[3];
    rootMap.getKeys().toArray(keys);
    assertEquals(keys[0], new ByteString(new byte[] { 0x01 }));
    assertEquals(keys[1], new UnsignedInteger(1));
    assertEquals(keys[2], new UnicodeString("asdf"));

    assertTrue(rootMap.get(keys[0]) instanceof Map);
    assertTrue(rootMap.get(keys[1]) instanceof Map);
    assertTrue(rootMap.get(keys[2]) instanceof Map);
}
 
Example #6
Source Project: webauthndemo   Author: google   File: AndroidSafetyNetAttestationStatement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Decodes a cbor representation of an AndroidSafetyNetAttestationStatement into the object
 * representation
 *
 * @param attStmt Cbor DataItem representation of the attestation statement to decode
 * @return Decoded AndroidSafetyNetAttestationStatement
 * @throws ResponseException Input was not a valid AndroidSafetyNetAttestationStatement DataItem
 */
public static AndroidSafetyNetAttestationStatement decode(DataItem attStmt)
    throws ResponseException {
  AndroidSafetyNetAttestationStatement result = new AndroidSafetyNetAttestationStatement();
  Map given = (Map) attStmt;
  for (DataItem data : given.getKeys()) {
    if (data instanceof UnicodeString) {
      if (((UnicodeString) data).getString().equals("ver")) {
        UnicodeString version = (UnicodeString) given.get(data);
        result.ver = version.getString();
      } else if (((UnicodeString) data).getString().equals("response")) {
        result.response = ((ByteString) (given.get(data))).getBytes();
      }
    }
  }
  if (result.response == null || result.ver == null)
    throw new ResponseException("Invalid JWT Cbor");
  return result;
}
 
Example #7
Source Project: webauthndemo   Author: google   File: AndroidSafetyNetAttestationStatementTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test method for
 * {@link com.google.webauthn.gaedemo.objects.AndroidSafetyNetAttestationStatement#encode()} and
 * {@link com.google.webauthn.gaedemo.objects.AndroidSafetyNetAttestationStatement#decode(co.nstant.in.cbor.model.DataItem)}.
 */
@Ignore
@Test
public void testEncode() {
  SecureRandom random = new SecureRandom();
  AndroidSafetyNetAttestationStatement attStmt = new AndroidSafetyNetAttestationStatement();
  attStmt.ver = "10";
  attStmt.response = new byte[20];
  random.nextBytes(attStmt.response);

  try {
    DataItem encoded = attStmt.encode();
    AndroidSafetyNetAttestationStatement decoded =
        AndroidSafetyNetAttestationStatement.decode(encoded);
    assertEquals(decoded, attStmt);
  } catch (CborException | ResponseException e) {
    fail(e.getMessage());
  }
}
 
Example #8
Source Project: cbor-java   Author: c-rack   File: MapEncoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void encode(Map map) throws CborException {
    Collection<DataItem> keys = map.getKeys();

    if (map.isChunked()) {
        encodeTypeChunked(MajorType.MAP);
    } else {
        encodeTypeAndLength(MajorType.MAP, keys.size());
    }

    if (keys.isEmpty()) {
        return;
    }

    if (map.isChunked()) {
        encodeNonCanonical(map);
        encoder.encode(SimpleValue.BREAK);
    } else {
        if (encoder.isCanonical()) {
            encodeCanonical(map);
        } else {
            encodeNonCanonical(map);
        }
    }
}
 
Example #9
Source Project: cbor-java   Author: c-rack   File: ByteStringDecoder.java    License: Apache License 2.0 6 votes vote down vote up
private ByteString decodeInfinitiveLength() throws CborException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    for (;;) {
        DataItem dataItem = decoder.decodeNext();
        if (dataItem == null) {
            throw new CborException("Unexpected end of stream");
        }
        MajorType majorType = dataItem.getMajorType();
        if (Special.BREAK.equals(dataItem)) {
            break;
        } else if (majorType == MajorType.BYTE_STRING) {
            ByteString byteString = (ByteString) dataItem;
            byte[] byteArray = byteString.getBytes();
            if (byteArray != null) {
                bytes.write(byteArray, 0, byteArray.length);
            }
        } else {
            throw new CborException("Unexpected major type " + majorType);
        }
    }
    return new ByteString(bytes.toByteArray());
}
 
Example #10
Source Project: cbor-java   Author: c-rack   File: EncoderDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws CborException {
    UnsignedInteger a = new UnsignedInteger(1);
    NegativeInteger x = new NegativeInteger(-2);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    CborEncoder encoder = new CborEncoder(byteArrayOutputStream);
    encoder.encode(a);
    encoder.encode(x);
    byte[] bytes = byteArrayOutputStream.toByteArray();
    DataItem object = CborDecoder.decode(bytes).get(0);
    Assert.assertEquals(a, object);
}
 
Example #11
Source Project: cbor-java   Author: c-rack   File: CborDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = CborException.class)
public void shouldThrowOnRationalNumberDecode1() throws CborException {
    List<DataItem> items = new CborBuilder().addTag(30).add(true).build();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CborEncoder encoder = new CborEncoder(baos);
    encoder.encode(items);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    CborDecoder decoder = new CborDecoder(bais);
    decoder.decode();
}
 
Example #12
Source Project: webauthndemo   Author: google   File: RsaKey.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] encode() throws CborException {
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  List<DataItem> dataItems =
      new CborBuilder().addMap().put(new UnsignedInteger(KTY_LABEL), new UnsignedInteger(kty))
          .put(new UnsignedInteger(ALG_LABEL), new NegativeInteger(alg.encodeToInt()))
          .put(new NegativeInteger(N_LABEL), new ByteString(n))
          .put(new NegativeInteger(E_LABEL), new ByteString(e)).end().build();
  new CborEncoder(output).encode(dataItems);
  return output.toByteArray();
}
 
Example #13
Source Project: cbor-java   Author: c-rack   File: Example69Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecode() throws CborException {
    InputStream inputStream = new ByteArrayInputStream(ENCODED_VALUE);
    CborDecoder decoder = new CborDecoder(inputStream);
    List<DataItem> dataItems = decoder.decode();
    Assert.assertArrayEquals(VALUE.toArray(), dataItems.toArray());
}
 
Example #14
Source Project: webauthndemo   Author: google   File: EccKey.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] encode() throws CborException {
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  List<DataItem> dataItems =
      new CborBuilder().addMap().put(new UnsignedInteger(KTY_LABEL), new UnsignedInteger(kty))
          .put(new UnsignedInteger(ALG_LABEL), new NegativeInteger(alg.encodeToInt()))
          .put(new NegativeInteger(CRV_LABEL), new UnsignedInteger(crv))
          .put(new NegativeInteger(X_LABEL), new ByteString(x))
          .put(new NegativeInteger(Y_LABEL), new ByteString(y)).end().build();
  new CborEncoder(output).encode(dataItems);
  return output.toByteArray();
}
 
Example #15
Source Project: cbor-java   Author: c-rack   File: Example50Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecode() throws CborException {
    InputStream inputStream = new ByteArrayInputStream(ENCODED_VALUE);
    CborDecoder decoder = new CborDecoder(inputStream);
    List<DataItem> dataItems = decoder.decode();
    Assert.assertArrayEquals(VALUE.toArray(), dataItems.toArray());
}
 
Example #16
Source Project: webauthndemo   Author: google   File: AttestationObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return Encoded byte array containing AttestationObject data
 * @throws CborException
 */
public byte[] encode() throws CborException {
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  List<DataItem> cbor =
      new CborBuilder().addMap().put("fmt", fmt).put("authData", authData.encode())
          .put(new UnicodeString("attStmt"), attStmt.encode()).end().build();
  new CborEncoder(output).encode(cbor);
  return output.toByteArray();
}
 
Example #17
Source Project: cbor-java   Author: c-rack   File: ArrayBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddFloat() {
    CborBuilder builder = new CborBuilder();
    List<DataItem> dataItems = builder.addArray().add(1.0f).end().build();
    assertEquals(1, dataItems.size());
    assertTrue(dataItems.get(0) instanceof Array);
    Array array = (Array) dataItems.get(0);
    assertEquals(1, array.getDataItems().size());
    assertTrue(array.getDataItems().get(0) instanceof HalfPrecisionFloat);
}
 
Example #18
Source Project: cbor-java   Author: c-rack   File: ByteStringDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecodeChunkedByteString() throws CborException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CborEncoder encoder = new CborEncoder(baos);
    encoder.encode(new CborBuilder().startByteString().add(new byte[] { '\0' }).add(new byte[] { 0x10 })
        .add(new byte[] { 0x13 }).end().build());
    byte[] encodedBytes = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(encodedBytes);
    CborDecoder decoder = new CborDecoder(bais);
    List<DataItem> dataItems = decoder.decode();
    assertNotNull(dataItems);
    assertEquals(1, dataItems.size());
}
 
Example #19
Source Project: cbor-java   Author: c-rack   File: Example76Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecode() throws CborException {
    InputStream inputStream = new ByteArrayInputStream(ENCODED_VALUE);
    CborDecoder decoder = new CborDecoder(inputStream);
    decoder.setAutoDecodeInfinitiveArrays(false);
    List<DataItem> dataItems = decoder.decode();
    Assert.assertArrayEquals(VALUE.toArray(), dataItems.toArray());
}
 
Example #20
Source Project: cbor-java   Author: c-rack   File: Example83Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecode() throws CborException {
    InputStream inputStream = new ByteArrayInputStream(ENCODED_VALUE);
    CborDecoder decoder = new CborDecoder(inputStream);
    List<DataItem> dataItems = decoder.decode();
    Assert.assertArrayEquals(VALUE.toArray(), dataItems.toArray());
}
 
Example #21
Source Project: cbor-java   Author: c-rack   File: Example74Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecode() throws CborException {
    InputStream inputStream = new ByteArrayInputStream(ENCODED_VALUE);
    CborDecoder decoder = new CborDecoder(inputStream);
    decoder.setAutoDecodeInfinitiveArrays(false);
    List<DataItem> dataItems = decoder.decode();
    Assert.assertArrayEquals(VALUE.toArray(), dataItems.toArray());
}
 
Example #22
Source Project: cbor-java   Author: c-rack   File: LanguageTaggedStringDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = CborException.class)
public void testExceptionOnNotSecondElementIsString() throws CborException {
    List<DataItem> items = new CborBuilder().addTag(38).addArray().add("en").add(true).end().build();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CborEncoder encoder = new CborEncoder(baos);
    encoder.encode(items);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    CborDecoder decoder = new CborDecoder(bais);
    decoder.decode();
}
 
Example #23
Source Project: cbor-java   Author: c-rack   File: ArrayBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddBoolean() {
    CborBuilder builder = new CborBuilder();
    List<DataItem> dataItems = builder.addArray().add(true).add(false).end().build();
    assertEquals(1, dataItems.size());
    assertTrue(dataItems.get(0) instanceof Array);
    Array array = (Array) dataItems.get(0);
    assertEquals(2, array.getDataItems().size());
    assertTrue(array.getDataItems().get(0) instanceof SimpleValue);
    assertTrue(array.getDataItems().get(1) instanceof SimpleValue);
}
 
Example #24
Source Project: cbor-java   Author: c-rack   File: AbstractSinglePrecisionFloatTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecode() throws CborException {
    InputStream inputStream = new ByteArrayInputStream(encodedValue);
    CborDecoder decoder = new CborDecoder(inputStream);
    DataItem dataItem = decoder.decodeNext();
    Assert.assertTrue(dataItem instanceof SinglePrecisionFloat);
    SinglePrecisionFloat singlePrecisionFloat = (SinglePrecisionFloat) dataItem;
    Assert.assertEquals(value, singlePrecisionFloat.getValue(), 0);
}
 
Example #25
Source Project: cbor-java   Author: c-rack   File: AbstractNumberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecode() throws CborException {
    InputStream inputStream = new ByteArrayInputStream(encodedValue);
    CborDecoder decoder = new CborDecoder(inputStream);
    DataItem dataItem = decoder.decodeNext();
    Assert.assertTrue(dataItem instanceof Number);
    Number number = (Number) dataItem;
    Assert.assertEquals(value, number.getValue());
}
 
Example #26
Source Project: cbor-java   Author: c-rack   File: CborDecoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Streaming decoding of an input stream. On each decoded DataItem, the callback
 * listener is invoked.
 *
 * @param dataItemListener the callback listener
 * @throws CborException if decoding failed
 */
public void decode(DataItemListener dataItemListener) throws CborException {
    Objects.requireNonNull(dataItemListener);
    DataItem dataItem = decodeNext();
    while (dataItem != null) {
        dataItemListener.onDataItem(dataItem);
        dataItem = decodeNext();
    }
}
 
Example #27
Source Project: cbor-java   Author: c-rack   File: ArrayBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddDouble() {
    CborBuilder builder = new CborBuilder();
    List<DataItem> dataItems = builder.addArray().add(1.0d).end().build();
    assertEquals(1, dataItems.size());
    assertTrue(dataItems.get(0) instanceof Array);
    Array array = (Array) dataItems.get(0);
    assertEquals(1, array.getDataItems().size());
    assertTrue(array.getDataItems().get(0) instanceof DoublePrecisionFloat);
}
 
Example #28
Source Project: cbor-java   Author: c-rack   File: CborDecoder.java    License: Apache License 2.0 5 votes vote down vote up
private DataItem decodeLanguageTaggedString(DataItem dataItem) throws CborException {
    if (!(dataItem instanceof Array)) {
        throw new CborException("Error decoding LanguageTaggedString: not an array");
    }

    Array array = (Array) dataItem;

    if (array.getDataItems().size() != 2) {
        throw new CborException("Error decoding LanguageTaggedString: array size is not 2");
    }

    DataItem languageDataItem = array.getDataItems().get(0);

    if (!(languageDataItem instanceof UnicodeString)) {
        throw new CborException("Error decoding LanguageTaggedString: first data item is not an UnicodeString");
    }

    DataItem stringDataItem = array.getDataItems().get(1);

    if (!(stringDataItem instanceof UnicodeString)) {
        throw new CborException("Error decoding LanguageTaggedString: second data item is not an UnicodeString");
    }

    UnicodeString language = (UnicodeString) languageDataItem;
    UnicodeString string = (UnicodeString) stringDataItem;

    return new LanguageTaggedString(language, string);
}
 
Example #29
Source Project: cbor-java   Author: c-rack   File: AbstractNumberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEncode() throws CborException {
    List<DataItem> dataItems = new CborBuilder().add(value).build();
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    CborEncoder encoder = new CborEncoder(byteOutputStream);
    encoder.encode(dataItems.get(0));
    Assert.assertArrayEquals(encodedValue, byteOutputStream.toByteArray());
}
 
Example #30
Source Project: cbor-java   Author: c-rack   File: CborEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Encode a single {@link DataItem}.
 *
 * @param dataItem the {@link DataItem} to encode. If null, encoder encodes a
 *                 {@link SimpleValue} NULL value.
 * @throws CborException if {@link DataItem} could not be encoded or there was
 *                       an problem with the {@link OutputStream}.
 */
public void encode(DataItem dataItem) throws CborException {
    if (dataItem == null) {
        dataItem = SimpleValue.NULL;
    }

    if (dataItem.hasTag()) {
        Tag tagDi = dataItem.getTag();
        encode(tagDi);
    }

    switch (dataItem.getMajorType()) {
    case UNSIGNED_INTEGER:
        unsignedIntegerEncoder.encode((UnsignedInteger) dataItem);
        break;
    case NEGATIVE_INTEGER:
        negativeIntegerEncoder.encode((NegativeInteger) dataItem);
        break;
    case BYTE_STRING:
        byteStringEncoder.encode((ByteString) dataItem);
        break;
    case UNICODE_STRING:
        unicodeStringEncoder.encode((UnicodeString) dataItem);
        break;
    case ARRAY:
        arrayEncoder.encode((Array) dataItem);
        break;
    case MAP:
        mapEncoder.encode((Map) dataItem);
        break;
    case SPECIAL:
        specialEncoder.encode((Special) dataItem);
        break;
    case TAG:
        tagEncoder.encode((Tag) dataItem);
        break;
    default:
        throw new CborException("Unknown major type");
    }
}