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

The following examples show how to use co.nstant.in.cbor.model.UnicodeString. 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: webauthndemo   Source 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 2
Source Project: webauthndemo   Source 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 3
/**
 * 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 4
Source Project: webauthndemo   Source File: CableRegistrationData.java    License: 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 5
Source Project: cbor-java   Source File: UnicodeStringEncoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void encode(UnicodeString dataItem) throws CborException {
    String string = dataItem.getString();
    if (dataItem.isChunked()) {
        encodeTypeChunked(MajorType.UNICODE_STRING);
        if (string != null) {
            encode(new UnicodeString(string));
        }
    } else if (string == null) {
        encoder.encode(SimpleValue.NULL);
    } else {
        byte[] bytes;
        bytes = string.getBytes(StandardCharsets.UTF_8);
        encodeTypeAndLength(MajorType.UNICODE_STRING, bytes.length);
        write(bytes);
    }
}
 
Example 6
Source Project: cbor-java   Source File: UnicodeStringDecoder.java    License: Apache License 2.0 6 votes vote down vote up
private UnicodeString 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.UNICODE_STRING) {
            UnicodeString unicodeString = (UnicodeString) dataItem;
            byte[] byteArray = unicodeString.toString().getBytes(StandardCharsets.UTF_8);
            bytes.write(byteArray, 0, byteArray.length);
        } else {
            throw new CborException("Unexpected major type " + majorType);
        }
    }
    return new UnicodeString(new String(bytes.toByteArray(), StandardCharsets.UTF_8));
}
 
Example 7
Source Project: cbor-java   Source 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 8
/**
 * 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 Project: webauthndemo   Source File: AttestationObject.java    License: 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 10
Source Project: webauthndemo   Source 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 11
@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 12
Source Project: webauthndemo   Source File: FidoU2fAttestationStatement.java    License: 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 13
Source Project: cbor-java   Source 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 14
Source Project: cbor-java   Source 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");
    }
}
 
Example 15
Source Project: cbor-java   Source File: UnicodeStringDecoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UnicodeString decode(int initialByte) throws CborException {
    long length = getLength(initialByte);
    if (length == INFINITY) {
        if (decoder.isAutoDecodeInfinitiveUnicodeStrings()) {
            return decodeInfinitiveLength();
        } else {
            UnicodeString unicodeString = new UnicodeString(null);
            unicodeString.setChunked(true);
            return unicodeString;
        }
    } else {
        return decodeFixedLength(length);
    }
}
 
Example 16
Source Project: cbor-java   Source File: AbstractStringTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEncode() throws CborException {
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    CborEncoder encoder = new CborEncoder(byteOutputStream);
    encoder.encode(new UnicodeString(value));
    Assert.assertArrayEquals(encodedValue, byteOutputStream.toByteArray());
}
 
Example 17
Source Project: cbor-java   Source File: AbstractStringTest.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 UnicodeString);
    UnicodeString unicodeString = (UnicodeString) dataItem;
    Assert.assertEquals(value, unicodeString.toString());
}
 
Example 18
Source Project: cbor-java   Source File: LanguageTaggedStringDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDecoding() throws CborException {
    List<DataItem> items = new CborBuilder().addTag(38).addArray().add("en").add("string").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);
    DataItem item = decoder.decodeNext();
    assertEquals(new LanguageTaggedString(new UnicodeString("en"), new UnicodeString("string")), item);
}
 
Example 19
Source Project: cbor-java   Source File: CborBuilder.java    License: Apache License 2.0 4 votes vote down vote up
public UnicodeStringBuilder<CborBuilder> startString(String string) {
    add(new UnicodeString(string).setChunked(true));
    return new UnicodeStringBuilder<CborBuilder>(this);
}
 
Example 20
Source Project: cbor-java   Source File: UnicodeStringDecoder.java    License: Apache License 2.0 4 votes vote down vote up
private UnicodeString decodeFixedLength(long length) throws CborException {
    return new UnicodeString(new String(decodeBytes(length), StandardCharsets.UTF_8));
}
 
Example 21
Source Project: cbor-java   Source File: AbstractBuilder.java    License: Apache License 2.0 4 votes vote down vote up
protected DataItem convert(String string) {
    return new UnicodeString(string);
}
 
Example 22
Source Project: cbor-java   Source File: Example48Test.java    License: Apache License 2.0 4 votes vote down vote up
public Example48Test() {
    DataItem di = new UnicodeString("2013-03-21T20:04:00Z");
    di.setTag(0);

    VALUE = new CborBuilder().add(di).build();
}
 
Example 23
Source Project: cbor-java   Source File: Example53Test.java    License: Apache License 2.0 4 votes vote down vote up
public Example53Test() {
    DataItem di = new UnicodeString("http://www.example.com");
    di.setTag(32);

    VALUE = new CborBuilder().add(di).build();
}
 
Example 24
Source Project: cbor-java   Source File: AbstractDecoderTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public UnicodeString decode(int initialByte) throws CborException {
    return null;
}
 
Example 25
Source Project: cbor-java   Source File: MapBuilderTest.java    License: 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());
}