com.fasterxml.jackson.dataformat.cbor.CBORParser Java Examples

The following examples show how to use com.fasterxml.jackson.dataformat.cbor.CBORParser. 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: AbstractDDiApiIntegrationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Convert CBOR to JSON equivalent.
 * 
 * @param input
 *            CBOR data to convert
 * @return Equivalent JSON string
 * @throws IOException
 *             Invalid CBOR input
 */
protected static String cborToJson(byte[] input) throws IOException {
    CBORFactory cborFactory = new CBORFactory();
    CBORParser cborParser = cborFactory.createParser(input);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter stringWriter = new StringWriter();
    JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter);
    while (cborParser.nextToken() != null) {
        jsonGenerator.copyCurrentEvent(cborParser);
    }
    jsonGenerator.flush();
    return stringWriter.toString();
}
 
Example #2
Source File: RSAKeyObject.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void decode(byte[] cbor) throws IOException {

        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        CBORParser parser = f.createParser(cbor);

        Map<String, Object> pkObjectMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
        });

        for (String key : pkObjectMap.keySet()) {
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                    "key : " + key + ", Value : " + pkObjectMap.get(key).toString());
            switch (key) {
                case "1":
                    kty = (int) pkObjectMap.get(key);
                    break;
                case "3":
                    alg = (int) pkObjectMap.get(key);
                    break;
                case "-1":
                    n = (byte[]) pkObjectMap.get(key);
                    break;
                case "-2":
                    e = (byte[]) pkObjectMap.get(key);
                    break;
            }
        }
    }
 
Example #3
Source File: FIDO2Extensions.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public int decodeExtensions(byte[] extensionBytes) throws IOException {
    CBORFactory f = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(f);
    CBORParser parser = f.createParser(extensionBytes);
    extensionMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {});

    //Return size of AttestedCredentialData
    int numRemainingBytes = 0;
    JsonToken leftoverCBORToken;
    while ((leftoverCBORToken = parser.nextToken()) != null) {
        numRemainingBytes += leftoverCBORToken.asByteArray().length;
    }
    return extensionBytes.length - numRemainingBytes;
}
 
Example #4
Source File: ECKeyObject.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void decode(byte[] cbor) throws IOException {

        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        CBORParser parser = f.createParser(cbor);

        Map<String, Object> pkObjectMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
        });

        for (String key : pkObjectMap.keySet()) {
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                    "key : " + key);
            switch (key) {
                case "1":
                    kty = (int) pkObjectMap.get(key);
                    break;
                case "-1":
                    crv = (int) pkObjectMap.get(key);
                    break;
                case "3":
                    alg = (int) pkObjectMap.get(key);
                    break;
                case "-2":
                    x = (byte[]) pkObjectMap.get(key);
                    break;
                case "-3":
                    y = (byte[]) pkObjectMap.get(key);
                    break;
            }
        }
    }
 
Example #5
Source File: RSAKeyObject.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void decode(byte[] cbor) throws IOException
    {
        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        CBORParser parser = f.createParser(cbor);

        Map<String, Object> pkobjectsmap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
        });

        for (String key : pkobjectsmap.keySet()) {
//            System.out.println("key : " + key + ", Value : " + pkobjectsmap.get(key).toString());
            switch (key) {
                case "1":
                    kty = (int) pkobjectsmap.get(key);
                    break;
                case "3":
                    alg = (int) pkobjectsmap.get(key);
                    break;
                case "-1":
                    n = (byte[]) pkobjectsmap.get(key);
                    break;
                case "-2":
                    e = (byte[]) pkobjectsmap.get(key);
                    break;
            }
        }
    }
 
Example #6
Source File: FIDO2Extensions.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public int decodeExtensions(byte[] extensionBytes) throws IOException
{
    CBORFactory cbf = new CBORFactory();
    CBORParser cbp = cbf.createParser(extensionBytes);
    extensionMap = (new ObjectMapper(cbf)).readValue(cbp, new TypeReference<Map<String, Object>>() {});
    int numRemainingBytes = 0;
    JsonToken leftoverCBORToken;
    while ((leftoverCBORToken = cbp.nextToken()) != null) {
        numRemainingBytes += leftoverCBORToken.asByteArray().length;
    }
    return extensionBytes.length - numRemainingBytes;
}
 
Example #7
Source File: ECKeyObject.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void decode(byte[] cbor) throws IOException {

        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        CBORParser parser = f.createParser(cbor);

        Map<String, Object> pkobjectsmap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
        });

        for (String key : pkobjectsmap.keySet()) {
//            System.out.println("key : " + key);
            switch (key) {
                case "1":
                    kty = (int) pkobjectsmap.get(key);
                    break;
                case "-1":
                    crv = (int) pkobjectsmap.get(key);
                    break;
                case "3":
                    alg = (int) pkobjectsmap.get(key);
                    break;
                case "-2":
                    x = (byte[]) pkobjectsmap.get(key);
                    break;
                case "-3":
                    y = (byte[]) pkobjectsmap.get(key);
                    break;
            }
        }
    }
 
Example #8
Source File: CborFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Deserializes a {@code JsonValue} by parsing the passed {@code bytes} with CBOR.
 *
 * @param bytes the bytes to parse with CBOR.
 * @return the parsed JsonValue.
 */
public static JsonValue readFrom(final byte[] bytes) {
    final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    try {
        final CBORParser parser = JACKSON_CBOR_FACTORY.createParser(bytes);
        return parseValue(parser, byteBuffer);
    } catch (final IOException | IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
        throw createJsonParseException(byteBuffer, e);
    }
}
 
Example #9
Source File: CborFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Deserializes a {@code JsonValue} by parsing the passed {@code bytes} with CBOR applying a {@code offset} and
 * {@code length}.
 *
 * @param bytes the bytes to parse with CBOR.
 * @param offset the offset where to start reading from.
 * @param length the lenght of how much bytes to read.
 * @return the parsed JsonValue.
 */
public static JsonValue readFrom(final byte[] bytes, final int offset, final int length) {
    // ensure that buffers position is zero so that offsets determined by CBORParser map directly to positions in this buffer.
    final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, offset, length).slice();
    try {
        final CBORParser parser = JACKSON_CBOR_FACTORY.createParser(bytes, offset, length);
        return parseValue(parser, byteBuffer);
    } catch (final IOException | IllegalArgumentException e) {
        throw createJsonParseException(byteBuffer, e);
    }
}
 
Example #10
Source File: CborFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Deserializes a {@code JsonValue} by parsing the passed {@code byteBuffer} with CBOR.
 *
 * @param byteBuffer the ByteBuffer to parse with CBOR.
 * @return the parsed JsonValue.
 */
public static JsonValue readFrom(final ByteBuffer byteBuffer) {
    // ensure that buffers position is zero so that offsets determined by CBORParser map directly to positions in this buffer.
    final ByteBuffer slicedByteBuffer = byteBuffer.slice();
    try {
        final CBORParser parser = JACKSON_CBOR_FACTORY.createParser(ByteBufferInputStream.of(slicedByteBuffer));
        return parseValue(parser, slicedByteBuffer);
    } catch (final IOException | IllegalArgumentException e) {
        throw createJsonParseException(slicedByteBuffer, e);
    }
}
 
Example #11
Source File: CborFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static JsonObject parseObject(final CBORParser parser, final ByteBuffer byteBuffer) throws IOException {
    final LinkedHashMap<String, JsonField> map = new LinkedHashMap<>();
    final long startOffset = parser.getTokenLocation().getByteOffset();
    while (parser.nextToken() == JsonToken.FIELD_NAME) {
        final String key = parser.currentName();
        final JsonField jsonField = JsonField.newInstance(key, parseValue(parser, byteBuffer));
        map.put(key, jsonField);
    }
    final long endOffset = parser.getTokenLocation().getByteOffset();
    return ImmutableJsonObject.of(map, getBytesFromInputSource(startOffset, endOffset, byteBuffer));
}
 
Example #12
Source File: CborFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static JsonArray parseArray(final CBORParser parser, final ByteBuffer byteBuffer) throws IOException {
    final LinkedList<JsonValue> list = new LinkedList<>();
    final long startOffset = parser.getTokenLocation().getByteOffset();
    while (parser.nextToken() != JsonToken.END_ARRAY) {
        final JsonValue jsonValue = parseValue(parser, byteBuffer, parser.currentToken());
        list.add(jsonValue);
    }
    final long endOffset = parser.getTokenLocation().getByteOffset();
    return ImmutableJsonArray.of(list, getBytesFromInputSource(startOffset, endOffset, byteBuffer));
}
 
Example #13
Source File: FIDO2AttestedCredentialData.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public int decodeAttCredData(byte[] data) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidParameterSpecException {
    int remainingDataIndex = 0;

    aaguid = new byte[16];
    credentialId = new byte[]{};
    System.arraycopy(data, 0, aaguid, 0, 16);
    remainingDataIndex += 16;

    skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "AAGUID : " + Base64.toBase64String(aaguid));

    byte[] lengthValue = new byte[2];
    System.arraycopy(data, remainingDataIndex, lengthValue, 0, 2);
    remainingDataIndex += 2;
    length = ByteBuffer.wrap(lengthValue).getShort();

    skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "length : " + length);

    credentialId = new byte[length];
    System.arraycopy(data, remainingDataIndex, credentialId, 0, length);
    remainingDataIndex += length;

    byte[] cbor = new byte[data.length - remainingDataIndex];
    System.arraycopy(data, remainingDataIndex, cbor, 0, data.length - remainingDataIndex);

    skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "cbor (hex): \n" + bytesToHexString(cbor, cbor.length));
    CBORFactory f = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(f);
    int kty = 0;
    CBORParser parser = f.createParser(cbor);
    Map<String, Object> pkObjectMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
    });

    skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "pkObjectMap: ");
    for(String key: pkObjectMap.keySet()){
        skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "Key: " + key + ", Object: " + pkObjectMap.get(key).toString());
    }
    kty = (int) pkObjectMap.get("1");
    skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "KTY = " + kty);
    if (kty == 2) {
        ECKeyObject eck = new ECKeyObject();
        eck.decode(cbor);

        int crv = eck.getCrv();
        skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "crv = " + crv);
        String curveString = skfsCommon.getCurveFromFIDOECCCurveID(crv);
        skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "curveString = " + curveString);
        skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "X = " + org.bouncycastle.util.encoders.Hex.toHexString(eck.getX()));
        skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "Y = " + org.bouncycastle.util.encoders.Hex.toHexString(eck.getY()));
        publicKey = cryptoCommon.getUserECPublicKey(eck.getX(), eck.getY(), curveString);

        fko = eck;
    } else {
        RSAKeyObject rko = new RSAKeyObject();
        rko.decode(cbor);


        RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(1,rko.getN()), new BigInteger(1,rko.getE()));
        publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);

        fko = rko;
    }

    //Return size of AttestedCredentialData
    skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "FIDO2AttestedCredentialData size (bytes: " + parser.getCurrentLocation().getByteOffset());
    return remainingDataIndex + (int) parser.getCurrentLocation().getByteOffset();
}
 
Example #14
Source File: FIDO2AttestationObject.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void decodeAttestationObject(String attestationObject) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidParameterSpecException {
    CBORFactory f = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(f);
    byte[] authenticatorData = null;
    Object attestationStmt = null;
    CBORParser parser = f.createParser(org.apache.commons.codec.binary.Base64.decodeBase64(attestationObject));
    Map<String, Object> attObjectMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
    });

    //Verify cbor is properly formatted cbor (no extra bytes)
    if(parser.nextToken() != null){
        throw new IllegalArgumentException("FIDO2AttestationObject contains invalid CBOR");
    }

    for (String key : attObjectMap.keySet()) {
        if (key.equalsIgnoreCase("fmt")) {
            attFormat = attObjectMap.get(key).toString();
        } else if (key.equalsIgnoreCase("authData")) {
            authenticatorData = (byte[]) attObjectMap.get(key);
        } else if (key.equalsIgnoreCase("attStmt")) {
            attestationStmt = attObjectMap.get(key);
        }
    }
    authData = new FIDO2AuthenticatorData();
    authData.decodeAuthData(authenticatorData);

    skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "ATTFORMAT = "  +attFormat);
    switch (attFormat) {
        case "fido-u2f":
            attStmt = new U2FAttestationStatment();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "packed":
            attStmt = new PackedAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "tpm":
            attStmt = new TPMAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "android-key":
            attStmt = new AndroidKeyAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "android-safetynet":
            attStmt = new AndroidSafetynetAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "none":
            attStmt = new NoneAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        default:
            throw new IllegalArgumentException("Invalid attestation format");
    }

}
 
Example #15
Source File: CborFactory.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static JsonValue parseValue(final CBORParser parser, final ByteBuffer byteBuffer) throws IOException {
    return parseValue(parser, byteBuffer, parser.nextToken());
}
 
Example #16
Source File: CborFactory.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static JsonValue parseValue(final CBORParser parser, final ByteBuffer byteBuffer,
        @Nullable final JsonToken currentToken)
        throws IOException {
    if (currentToken == null) {
        throw new IOException("Unexpected end of input while expecting value.");
    }
    switch (currentToken) {
        case START_OBJECT:
            return parseObject(parser, byteBuffer);
        case START_ARRAY:
            return parseArray(parser, byteBuffer);
        case VALUE_STRING:
            return ImmutableJsonString.of(parser.getValueAsString());
        case VALUE_NUMBER_INT:
            return getIntegerOrLong(parser.getLongValue());
        case VALUE_NUMBER_FLOAT:
            return ImmutableJsonDouble.of(parser.getDoubleValue());
        case VALUE_TRUE:
            return ImmutableJsonBoolean.TRUE;
        case VALUE_FALSE:
            return ImmutableJsonBoolean.FALSE;
        case VALUE_NULL:
            return ImmutableJsonNull.getInstance();

        // Unexpected cases:
        case END_ARRAY:
        case FIELD_NAME:
        case VALUE_EMBEDDED_OBJECT:
        case END_OBJECT:
            throw new IOException(
                    "Encountered unexpected token " + parser.currentToken()
                            + " at position " + parser.getCurrentLocation()
                            + " while parsing CBOR value.");

            // Programming errors:
        default:
        case NOT_AVAILABLE:
            // This is a blocking parser that should never return this value.
            throw new IOException("CBORParser returned unexpected token type: " + parser.currentToken());

    }
}