Search in sources :

Example 6 with CBORObject

use of com.upokecenter.cbor.CBORObject in project leshan by eclipse.

the class SenMLCborPackSerDes method deserializeFromCbor.

public SenMLPack deserializeFromCbor(Collection<CBORObject> objects) throws SenMLException {
    try {
        SenMLPack senMLPack = new SenMLPack();
        for (CBORObject o : objects) {
            SenMLRecord record = new SenMLRecord();
            CBORObject bn = o.get(-2);
            if (bn != null && bn.getType() == CBORType.TextString)
                record.setBaseName(bn.AsString());
            CBORObject bt = o.get(-3);
            if (bt != null && bt.isNumber())
                record.setBaseTime(bt.AsNumber().ToInt64Checked());
            CBORObject n = o.get(0);
            if (n != null && n.getType() == CBORType.TextString)
                record.setName(n.AsString());
            CBORObject t = o.get(6);
            if (t != null && t.isNumber())
                record.setTime(t.AsNumber().ToInt64Checked());
            CBORObject v = o.get(2);
            boolean hasValue = false;
            if (v != null && v.isNumber()) {
                CBORNumber number = v.AsNumber();
                switch(number.getKind()) {
                    case Integer:
                    case EInteger:
                        if (number.IsNegative()) {
                            if (number.CanFitInInt64()) {
                                record.setNumberValue(number.ToInt64Unchecked());
                            } else {
                                record.setNumberValue((BigInteger) v.ToObject(BigInteger.class));
                            }
                        } else {
                            if (number.CanFitInInt64()) {
                                record.setNumberValue(number.ToInt64Unchecked());
                            } else if (number.ToEIntegerIfExact().GetSignedBitLengthAsInt64() == 64) {
                                record.setNumberValue(ULong.valueOf(number.ToInt64Unchecked()));
                            } else {
                                record.setNumberValue((BigInteger) v.ToObject(BigInteger.class));
                            }
                        }
                        break;
                    case Double:
                    case EFloat:
                    case EDecimal:
                        if (v.AsNumber().CanFitInDouble()) {
                            record.setNumberValue(v.AsDoubleValue());
                        } else {
                            record.setNumberValue((BigDecimal) v.ToObject(BigDecimal.class));
                        }
                        break;
                    default:
                        throw new SenMLException("Invalid SenML record : unexpected kind of number %s is not supported in %s", number.getKind(), o);
                }
                hasValue = true;
            }
            CBORObject vb = o.get(4);
            if (vb != null && vb.getType() == CBORType.Boolean) {
                record.setBooleanValue(vb.AsBoolean());
                hasValue = true;
            }
            CBORObject vs = o.get(3);
            if (vs != null && vs.getType() == CBORType.TextString) {
                record.setStringValue(vs.AsString());
                hasValue = true;
            }
            CBORObject vlo = o.get("vlo");
            if (vlo != null && vlo.getType() == CBORType.TextString) {
                record.setObjectLinkValue(vlo.AsString());
                hasValue = true;
            }
            CBORObject vd = o.get(8);
            if (vd != null && vd.getType() == CBORType.ByteString) {
                record.setOpaqueValue(vd.GetByteString());
                hasValue = true;
            }
            if (!allowNoValue && !hasValue)
                throw new SenMLException("Invalid SenML record : record must have a value (v,vb,vlo,vd,vs) : %s", o);
            senMLPack.addRecord(record);
        }
        return senMLPack;
    } catch (IllegalArgumentException | IllegalStateException e) {
        throw new SenMLException(e, "Unable to serialize SenML in CBOR");
    }
}
Also used : BigInteger(java.math.BigInteger) SenMLPack(org.eclipse.leshan.senml.SenMLPack) SenMLRecord(org.eclipse.leshan.senml.SenMLRecord) SenMLException(org.eclipse.leshan.senml.SenMLException) CBORNumber(com.upokecenter.cbor.CBORNumber) CBORObject(com.upokecenter.cbor.CBORObject)

Example 7 with CBORObject

use of com.upokecenter.cbor.CBORObject in project leshan by eclipse.

the class SenMLCborPackSerDes method serializeToCbor.

public byte[] serializeToCbor(SenMLPack pack) throws SenMLException {
    try (OutputStream stream = new ByteArrayOutputStream()) {
        CBORObject cborArray = CBORObject.NewArray();
        for (SenMLRecord record : pack.getRecords()) {
            CBORObject cborRecord = newMap();
            if (record.getBaseName() != null && !record.getBaseName().isEmpty()) {
                cborRecord.Add(-2, record.getBaseName());
            }
            if (record.getBaseTime() != null) {
                cborRecord.Add(-3, record.getBaseTime());
            }
            if (record.getName() != null && !record.getName().isEmpty()) {
                cborRecord.Add(0, record.getName());
            }
            if (record.getTime() != null) {
                cborRecord.Add(6, record.getTime());
            }
            Type type = record.getType();
            if (type != null) {
                switch(record.getType()) {
                    case NUMBER:
                        Number value = record.getNumberValue();
                        if (value instanceof Byte) {
                            cborRecord.Add(2, value.byteValue());
                        } else if (value instanceof Short) {
                            cborRecord.Add(2, value.shortValue());
                        } else if (value instanceof Integer) {
                            cborRecord.Add(2, value.intValue());
                        } else if (value instanceof Long) {
                            cborRecord.Add(2, value.longValue());
                        } else if (value instanceof BigInteger) {
                            cborRecord.Add(2, value);
                        } else // unsigned integer
                        if (value instanceof ULong) {
                            cborRecord.Add(2, NumberUtil.unsignedLongToEInteger(((ULong) value).longValue()));
                        } else // floating-point
                        if (value instanceof Float) {
                            cborRecord.Add(2, value.floatValue());
                        } else if (value instanceof Double) {
                            cborRecord.Add(2, value.doubleValue());
                        } else if (value instanceof BigDecimal) {
                            cborRecord.Add(2, value);
                        }
                        break;
                    case BOOLEAN:
                        cborRecord.Add(4, record.getBooleanValue());
                        break;
                    case OBJLNK:
                        cborRecord.Add("vlo", record.getObjectLinkValue());
                        break;
                    case OPAQUE:
                        cborRecord.Add(8, record.getOpaqueValue());
                        break;
                    case STRING:
                        cborRecord.Add(3, record.getStringValue());
                        break;
                    default:
                        break;
                }
            } else {
                if (!allowNoValue) {
                    throw new SenMLException("Invalid SenML record : record must have a value (v,vb,vlo,vd,vs) : %s", record);
                }
            }
            cborArray.Add(cborRecord);
        }
        return cborArray.EncodeToBytes();
    } catch (IllegalArgumentException | IllegalStateException | IOException e) {
        throw new SenMLException(e, "Unable to serialize SenML in CBOR");
    }
}
Also used : ULong(org.eclipse.leshan.core.util.datatype.ULong) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SenMLRecord(org.eclipse.leshan.senml.SenMLRecord) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) BigDecimal(java.math.BigDecimal) BigInteger(java.math.BigInteger) Type(org.eclipse.leshan.senml.SenMLRecord.Type) CBORType(com.upokecenter.cbor.CBORType) CBORNumber(com.upokecenter.cbor.CBORNumber) ULong(org.eclipse.leshan.core.util.datatype.ULong) BigInteger(java.math.BigInteger) SenMLException(org.eclipse.leshan.senml.SenMLException) CBORObject(com.upokecenter.cbor.CBORObject)

Example 8 with CBORObject

use of com.upokecenter.cbor.CBORObject in project californium by eclipse.

the class RequestDecryptor method decrypt.

/**
 * @param db the context database used
 * @param request the request to decrypt
 * @param ctx the OSCore context
 *
 * @return the decrypted request
 *
 * @throws CoapOSException if decryption fails
 */
public static Request decrypt(OSCoreCtxDB db, Request request, OSCoreCtx ctx) throws CoapOSException {
    discardEOptions(request);
    byte[] protectedData = request.getPayload();
    Encrypt0Message enc;
    OptionSet uOptions = request.getOptions();
    try {
        enc = decompression(protectedData, request);
    } catch (OSException e) {
        LOGGER.error(ErrorDescriptions.FAILED_TO_DECODE_COSE);
        throw new CoapOSException(ErrorDescriptions.FAILED_TO_DECODE_COSE, ResponseCode.BAD_OPTION);
    }
    CBORObject kid = enc.findAttribute(HeaderKeys.KID);
    if (kid == null || !kid.getType().equals(CBORType.ByteString)) {
        LOGGER.error(ErrorDescriptions.MISSING_KID);
        throw new CoapOSException(ErrorDescriptions.FAILED_TO_DECODE_COSE, ResponseCode.BAD_OPTION);
    }
    byte[] rid = kid.GetByteString();
    // Retrieve Context ID (kid context)
    CBORObject kidContext = enc.findAttribute(CBORObject.FromObject(10));
    byte[] contextID = null;
    if (kidContext != null) {
        contextID = kidContext.GetByteString();
    }
    // Perform context re-derivation procedure if triggered or ongoing
    try {
        ctx = ContextRederivation.incomingRequest(db, ctx, contextID, rid);
    } catch (OSException e) {
        LOGGER.error(ErrorDescriptions.CONTEXT_REGENERATION_FAILED);
        throw new CoapOSException(ErrorDescriptions.CONTEXT_REGENERATION_FAILED, ResponseCode.BAD_REQUEST);
    }
    if (ctx == null) {
        LOGGER.error(ErrorDescriptions.CONTEXT_NOT_FOUND);
        throw new CoapOSException(ErrorDescriptions.CONTEXT_NOT_FOUND, ResponseCode.UNAUTHORIZED);
    }
    byte[] plaintext;
    try {
        plaintext = decryptAndDecode(enc, request, ctx, null);
    } catch (OSException e) {
        // First check for replay exceptions
        if (e.getMessage().equals(ErrorDescriptions.REPLAY_DETECT)) {
            LOGGER.error(ErrorDescriptions.REPLAY_DETECT);
            throw new CoapOSException(ErrorDescriptions.REPLAY_DETECT, ResponseCode.UNAUTHORIZED);
        }
        // Otherwise return generic error message
        LOGGER.error(ErrorDescriptions.DECRYPTION_FAILED);
        throw new CoapOSException(ErrorDescriptions.DECRYPTION_FAILED, ResponseCode.BAD_REQUEST);
    }
    // Check if parsing of request plaintext succeeds
    try {
        DatagramReader reader = new DatagramReader(new ByteArrayInputStream(plaintext));
        ctx.setCoAPCode(Code.valueOf(reader.read(CoAP.MessageFormat.CODE_BITS)));
        // resets option so eOptions gets priority during parse
        request.setOptions(EMPTY);
        new UdpDataParser().parseOptionsAndPayload(reader, request);
    } catch (Exception e) {
        LOGGER.error(ErrorDescriptions.DECRYPTION_FAILED);
        throw new CoapOSException(ErrorDescriptions.DECRYPTION_FAILED, ResponseCode.BAD_REQUEST);
    }
    OptionSet eOptions = request.getOptions();
    eOptions = OptionJuggle.merge(eOptions, uOptions);
    request.setOptions(eOptions);
    // We need the kid value on layer level
    request.getOptions().setOscore(rid);
    // Associate the Token with the context used
    db.addContext(request.getToken(), ctx);
    // Set information about the OSCORE context used in the endpoint context of this request
    OSCoreEndpointContextInfo.receivingRequest(ctx, request);
    return OptionJuggle.setRealCodeRequest(request, ctx.getCoAPCode());
}
Also used : Encrypt0Message(org.eclipse.californium.cose.Encrypt0Message) UdpDataParser(org.eclipse.californium.core.network.serialization.UdpDataParser) ByteArrayInputStream(java.io.ByteArrayInputStream) DatagramReader(org.eclipse.californium.elements.util.DatagramReader) OptionSet(org.eclipse.californium.core.coap.OptionSet) CBORObject(com.upokecenter.cbor.CBORObject)

Example 9 with CBORObject

use of com.upokecenter.cbor.CBORObject in project californium by eclipse.

the class Encrypt0Message method EncodeCBORObject.

/**
 * Internal function used to construct the CBORObject
 *
 * @return the constructed CBORObject
 * @throws CoseException if the content has not yet been encrypted
 */
@Override
protected CBORObject EncodeCBORObject() throws CoseException {
    if (rgbEncrypt == null)
        throw new CoseException("Encrypt function not called");
    CBORObject obj = CBORObject.NewArray();
    if (objProtected.size() > 0)
        obj.Add(objProtected.EncodeToBytes());
    else
        obj.Add(CBORObject.FromObject(new byte[0]));
    obj.Add(objUnprotected);
    if (emitContent)
        obj.Add(rgbEncrypt);
    else
        obj.Add(CBORObject.Null);
    return obj;
}
Also used : CBORObject(com.upokecenter.cbor.CBORObject)

Example 10 with CBORObject

use of com.upokecenter.cbor.CBORObject in project californium by eclipse.

the class EncryptCommon method getAADBytes.

// Method taken from EncryptCommon in COSE. This will provide the full AAD / Encrypt0-structure.
private byte[] getAADBytes() {
    CBORObject obj = CBORObject.NewArray();
    obj.Add(context);
    if (objProtected.size() == 0) {
        obj.Add(CBORObject.FromObject(Bytes.EMPTY));
    } else {
        obj.Add(objProtected.EncodeToBytes());
    }
    obj.Add(CBORObject.FromObject(externalData));
    return obj.EncodeToBytes();
}
Also used : CBORObject(com.upokecenter.cbor.CBORObject)

Aggregations

CBORObject (com.upokecenter.cbor.CBORObject)30 CBORException (com.upokecenter.cbor.CBORException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 CBORNumber (com.upokecenter.cbor.CBORNumber)2 CBORType (com.upokecenter.cbor.CBORType)2 BigInteger (java.math.BigInteger)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 OptionSet (org.eclipse.californium.core.coap.OptionSet)2 Request (org.eclipse.californium.core.coap.Request)2 UdpDataParser (org.eclipse.californium.core.network.serialization.UdpDataParser)2 Encrypt0Message (org.eclipse.californium.cose.Encrypt0Message)2 DatagramReader (org.eclipse.californium.elements.util.DatagramReader)2 SenMLException (org.eclipse.leshan.senml.SenMLException)2 SenMLRecord (org.eclipse.leshan.senml.SenMLRecord)2 RecoveryCertificateQrCode (ch.admin.bag.covidcertificate.service.domain.RecoveryCertificateQrCode)1 VaccinationCertificateQrCode (ch.admin.bag.covidcertificate.service.domain.VaccinationCertificateQrCode)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1