co.nstant.in.cbor.model.Map Java Examples

The following examples show how to use co.nstant.in.cbor.model.Map. 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 File: AuthenticatorData.java    From webauthndemo with 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 #2
Source File: MapBuilderTest.java    From cbor-java with 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 #3
Source File: MapDecoder.java    From cbor-java with Apache License 2.0 6 votes vote down vote up
private Map decodeInfinitiveLength() throws CborException {
    Map map = new Map();
    map.setChunked(true);
    if (decoder.isAutoDecodeInfinitiveMaps()) {
        for (;;) {
            DataItem key = decoder.decodeNext();
            if (Special.BREAK.equals(key)) {
                break;
            }
            DataItem value = decoder.decodeNext();
            if (key == null || value == null) {
                throw new CborException("Unexpected end of stream");
            }
            if (decoder.isRejectDuplicateKeys() && map.get(key) != null) {
                throw new CborException("Duplicate key found in map");
            }
            map.put(key, value);
        }
    }
    return map;
}
 
Example #4
Source File: MapEncoder.java    From cbor-java with 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 #5
Source File: CableRegistrationData.java    From webauthndemo with Apache License 2.0 6 votes vote down vote up
public static CableRegistrationData parseFromCbor(DataItem cborCableData) {
  CableRegistrationData cableData = new CableRegistrationData();

  Map cborMap = (Map) cborCableData;

  for (DataItem data : cborMap.getKeys()) {
    if (data instanceof UnicodeString) {
      switch (((UnicodeString) data).getString()) {
        case "version":
          cableData.versions = new ArrayList<>();
          cableData.versions.add(((UnsignedInteger) cborMap.get(data)).getValue().intValue());
          break;
        case "maxVersion":
          cableData.maxVersion = ((UnsignedInteger) cborMap.get(data)).getValue().intValue();
          break;
        case "authenticatorPublicKey":
          cableData.publicKey = ((ByteString) cborMap.get(data)).getBytes();
          break;
      }
    }
  }
  return cableData;
}
 
Example #6
Source File: AndroidSafetyNetAttestationStatement.java    From webauthndemo with 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 File: PackedAttestationStatement.java    From webauthndemo with 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 #8
Source File: AuthenticatorTest.java    From android-webauthn-authenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Go through the whole dance of creating a new credential and generating an assertion
 * from the credential. Ensure that the signature is valid.
 * @throws VirgilException
 * @throws WebAuthnException
 * @throws CborException
 */
@Test
public void makeCredentialAndGetAssertionWithAllowCredential() throws VirgilException, WebAuthnException, CborException {
    AuthenticatorMakeCredentialOptions makeCredentialOptions = AuthenticatorMakeCredentialOptions.fromJSON(MAKE_CREDENTIAL_JSON);
    AttestationObject attObj = authenticator.makeCredential(makeCredentialOptions);
    byte[] cborEncoded = attObj.asCBOR();

    ByteArrayInputStream bais = new ByteArrayInputStream(cborEncoded);
    Map decoded = (Map) new CborDecoder(bais).decode().get(0);
    String fmt = ((UnicodeString) decoded.get(new UnicodeString("fmt"))).getString();
    assertEquals(fmt, "none");

    byte[] credentialId = attObj.getCredentialId();

    // Now let's see if we can generate an assertion based on the returned credential ID
    AuthenticatorGetAssertionOptions getAssertionOptions = AuthenticatorGetAssertionOptions.fromJSON(GET_ASSERTION_JSON);
    //getAssertionOptions.allowCredentialDescriptorList.clear();
    getAssertionOptions.allowCredentialDescriptorList.add(new PublicKeyCredentialDescriptor("public-key", credentialId, null));

    AuthenticatorGetAssertionResult getAssertionResult = authenticator.getAssertion(getAssertionOptions, new CredentialSelector() {
        @Override
        public PublicKeyCredentialSource selectFrom(List<PublicKeyCredentialSource> credentialList) {
            return credentialList.get(0);
        }
    });

    ByteBuffer resultBuf = ByteBuffer.allocate(getAssertionOptions.clientDataHash.length + getAssertionResult.authenticatorData.length);
    resultBuf.put(getAssertionResult.authenticatorData);
    resultBuf.put(getAssertionOptions.clientDataHash);
    byte[] signedData = resultBuf.array();
    List<PublicKeyCredentialSource> sources = this.credentialSafe.getKeysForEntity(makeCredentialOptions.rpEntity.id);
    PublicKeyCredentialSource source = sources.get(sources.size() - 1);
    KeyPair keyPair = this.credentialSafe.getKeyPairByAlias(source.keyPairAlias);
    assertTrue(this.cryptography.verifySignature(keyPair.getPublic(), signedData, getAssertionResult.signature));
}
 
Example #9
Source File: MapDecoderTest.java    From cbor-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUseLastOfDuplicateKeysByDefault() throws CborException {
    byte[] bytes = new byte[] { (byte) 0xa2, 0x01, 0x01, 0x01, 0x02 };
    List<DataItem> decoded = CborDecoder.decode(bytes);
    Map map = (Map) decoded.get(0);
    assertEquals(map.getKeys().size(), 1);
    assertEquals(map.get(new UnsignedInteger(1)), new UnsignedInteger(2));
}
 
Example #10
Source File: MapDecoder.java    From cbor-java with Apache License 2.0 5 votes vote down vote up
private Map decodeFixedLength(long length) throws CborException {
    Map map = new Map(getPreallocationSize(length));
    for (long i = 0; i < length; i++) {
        DataItem key = decoder.decodeNext();
        DataItem value = decoder.decodeNext();
        if (key == null || value == null) {
            throw new CborException("Unexpected end of stream");
        }
        if (decoder.isRejectDuplicateKeys() && map.get(key) != null) {
            throw new CborException("Duplicate key found in map");
        }
        map.put(key, value);
    }
    return map;
}
 
Example #11
Source File: MapDecoder.java    From cbor-java with Apache License 2.0 5 votes vote down vote up
@Override
public Map decode(int initialByte) throws CborException {
    long length = getLength(initialByte);
    if (length == INFINITY) {
        return decodeInfinitiveLength();
    } else {
        return decodeFixedLength(length);
    }
}
 
Example #12
Source File: CborEncoder.java    From cbor-java with 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");
    }
}
 
Example #13
Source File: AttestationObject.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
/**
 * @param attestationObject
 * @return AttestationObject created from the provided byte array
 * @throws CborException
 * @throws ResponseException
 */
public static AttestationObject decode(byte[] attestationObject)
    throws CborException, ResponseException {
  AttestationObject result = new AttestationObject();
  List<DataItem> dataItems = CborDecoder.decode(attestationObject);

  if (dataItems.size() == 1 && dataItems.get(0) instanceof Map) {
    DataItem attStmt = null;
    Map attObjMap = (Map) dataItems.get(0);
    for (DataItem key : attObjMap.getKeys()) {
      if (key instanceof UnicodeString) {
        switch(((UnicodeString) key).getString()) {
          case "fmt":
            UnicodeString value = (UnicodeString) attObjMap.get(key);
            result.fmt = value.getString();
            break;
          case "authData":
            byte[] authData = ((ByteString) attObjMap.get(key)).getBytes();
            result.authData = AuthenticatorData.decode(authData);
            break;
          case "attStmt":
            attStmt = attObjMap.get(key);
            break;
            
        }
      }
    }

    if (attStmt != null) {
      result.attStmt = AttestationStatement.decode(result.fmt, attStmt);
    }

  }
  return result;
}
 
Example #14
Source File: FidoU2fAttestationStatement.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
@Override
DataItem encode() throws CborException {
  Map result = new Map();
  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);
  result.put(new UnicodeString("sig"), new ByteString(sig));

  return result;
}
 
Example #15
Source File: AndroidSafetyNetAttestationStatement.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
@Override
DataItem encode() throws CborException {
  Map map = new Map();
  map.put(new UnicodeString("ver"), new UnicodeString(ver));
  map.put(new UnicodeString("response"), new ByteString(response));
  return map;
}
 
Example #16
Source File: CborBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder<CborBuilder> addMap() {
    Map map = new Map();
    add(map);
    return new MapBuilder<CborBuilder>(this, map);
}
 
Example #17
Source File: CborBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder<CborBuilder> startMap() {
    Map map = new Map();
    map.setChunked(true);
    add(map);
    return new MapBuilder<CborBuilder>(this, map);
}
 
Example #18
Source File: MapEncoder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
private void encodeCanonical(Map map) throws CborException {
    /**
     * From https://tools.ietf.org/html/rfc7049#section-3.9
     * 
     * Canonical CBOR
     * 
     * The keys in every map must be sorted lowest value to highest. Sorting is
     * performed on the bytes of the representation of the key data items without
     * paying attention to the 3/5 bit splitting for major types. (Note that this
     * rule allows maps that have keys of different types, even though that is
     * probably a bad practice that could lead to errors in some canonicalization
     * implementations.) The sorting rules are:
     * 
     * If two keys have different lengths, the shorter one sorts earlier;
     * 
     * If two keys have the same length, the one with the lower value in (byte-wise)
     * lexical order sorts earlier.
     */

    TreeMap<byte[], byte[]> sortedMap = new TreeMap<>(new Comparator<byte[]>() {

        @Override
        public int compare(byte[] o1, byte[] o2) {
            if (o1.length < o2.length) {
                return -1;
            }
            if (o1.length > o2.length) {
                return 1;
            }
            for (int i = 0; i < o1.length; i++) {
                if (o1[i] < o2[i]) {
                    return -1;
                }
                if (o1[i] > o2[i]) {
                    return 1;
                }
            }
            return 0;
        }

    });

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    CborEncoder e = new CborEncoder(byteArrayOutputStream);
    for (DataItem key : map.getKeys()) {
        // Key
        e.encode(key);
        byte[] keyBytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.reset();
        // Value
        e.encode(map.get(key));
        byte[] valueBytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.reset();
        sortedMap.put(keyBytes, valueBytes);
    }
    for (java.util.Map.Entry<byte[], byte[]> entry : sortedMap.entrySet()) {
        write(entry.getKey());
        write(entry.getValue());
    }
}
 
Example #19
Source File: MapEncoder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
private void encodeNonCanonical(Map map) throws CborException {
    for (DataItem key : map.getKeys()) {
        encoder.encode(key);
        encoder.encode(map.get(key));
    }
}
 
Example #20
Source File: NoneAttestationStatement.java    From webauthndemo with Apache License 2.0 4 votes vote down vote up
@Override
DataItem encode() throws CborException {
  Map result = new Map();
  return result;
}
 
Example #21
Source File: MapBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder(T parent, Map map) {
    super(parent);
    this.map = map;
}
 
Example #22
Source File: MapBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder<MapBuilder<T>> putMap(DataItem key) {
    Map nestedMap = new Map();
    put(key, nestedMap);
    return new MapBuilder<>(this, nestedMap);
}
 
Example #23
Source File: MapBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder<MapBuilder<T>> putMap(long key) {
    Map nestedMap = new Map();
    put(convert(key), nestedMap);
    return new MapBuilder<>(this, nestedMap);
}
 
Example #24
Source File: MapBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder<MapBuilder<T>> putMap(String key) {
    Map nestedMap = new Map();
    put(convert(key), nestedMap);
    return new MapBuilder<>(this, nestedMap);
}
 
Example #25
Source File: MapBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder<MapBuilder<T>> startMap(DataItem key) {
    Map nestedMap = new Map();
    nestedMap.setChunked(true);
    put(key, nestedMap);
    return new MapBuilder<>(this, nestedMap);
}
 
Example #26
Source File: ArrayBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder<ArrayBuilder<T>> addMap() {
    Map nestedMap = new Map();
    add(nestedMap);
    return new MapBuilder<ArrayBuilder<T>>(this, nestedMap);
}
 
Example #27
Source File: ArrayBuilder.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
public MapBuilder<ArrayBuilder<T>> startMap() {
    Map nestedMap = new Map();
    nestedMap.setChunked(true);
    add(nestedMap);
    return new MapBuilder<ArrayBuilder<T>>(this, nestedMap);
}
 
Example #28
Source File: MapBuilderTest.java    From cbor-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testMapBuilder() {
    List<DataItem> dataItems = new CborBuilder()
            .addMap()
                .put(new UnicodeString("key"), new UnicodeString("value"))
                .put(1, true)
                .put(2, "value".getBytes())
                .put(3, 1.0d)
                .put(4, 1.0f)
                .put(5, 1L)
                .put(6, "value")
                .put("7", true)
                .put("8", "value".getBytes())
                .put("9", 1.0d)
                .put("10", 1.0f)
                .put("11", 1L)
                .put("12", "value")
                .putMap(13)
                .end()
                .putMap("14").end()
                .putMap(new UnsignedInteger(15)).end()
                .putArray(16).end()
                .putArray("17").end()
                .putArray(new UnsignedInteger(18)).end()
                .addKey(19).value(true)
                .addKey(20).value("value".getBytes())
                .addKey(21).value(1.0d)
                .addKey(22).value(1.0f)
                .addKey(23).value(1L)
                .addKey(24).value("value")
                .addKey("25").value(true)
                .addKey("26").value("value".getBytes())
                .addKey("27").value(1.0d)
                .addKey("28").value(1.0f)
                .addKey("29").value(1L)
                .addKey("30").value("value")
            .end()
            .startMap()
                .startArray(1).end()
                .startArray(new UnsignedInteger(2)).end()
            .end()
            .build();
    assertEquals(2, dataItems.size());
    assertTrue(dataItems.get(0) instanceof Map);
    Map map = (Map) dataItems.get(0);
    assertEquals(31, map.getKeys().size());
}