Search in sources :

Example 16 with CBORObject

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

the class MultiFormat method handleGET.

@Override
public void handleGET(CoapExchange exchange) {
    // get request to read out details
    Request request = exchange.advanced().getRequest();
    // successively create response
    Response response = new Response(CONTENT);
    String format = null;
    switch(exchange.getRequestOptions().getAccept()) {
        case UNDEFINED:
        case TEXT_PLAIN:
            response.getOptions().setContentFormat(TEXT_PLAIN);
            format = "Status type: \"%s\"\nCode: \"%s\"\nMID: %d\nAccept: %d";
            break;
        case APPLICATION_XML:
            response.getOptions().setContentFormat(APPLICATION_XML);
            // should fit 64 bytes
            format = "<msg type=\"%s\" code=\"%s\" mid=\"%d\" accept=\"%d\" />";
            break;
        case APPLICATION_JSON:
            response.getOptions().setContentFormat(APPLICATION_JSON);
            // should fit 64 bytes
            format = "{ \"type\":\"%s\", \"code\":\"%s\", \"mid\":%d, \"accept\":%d }";
            break;
        case APPLICATION_CBOR:
            response.getOptions().setContentFormat(APPLICATION_CBOR);
            CBORObject map = CBORObject.NewMap();
            map.set(CBORObject.FromObject("type"), CBORObject.FromObject(request.getType().name()));
            map.set(CBORObject.FromObject("code"), CBORObject.FromObject(request.getCode().name()));
            map.set(CBORObject.FromObject("mid"), CBORObject.FromObject(request.getMID()));
            map.set(CBORObject.FromObject("accept"), CBORObject.FromObject(request.getOptions().getAccept()));
            response.setPayload(map.EncodeToBytes());
            // should fit 64 bytes
            break;
        default:
            response = new Response(NOT_ACCEPTABLE);
            format = "text/plain, application/xml, application/json, or application/cbor only";
            break;
    }
    if (format != null) {
        response.setPayload(String.format(format, request.getType(), request.getCode(), request.getMID(), request.getOptions().getAccept()));
    }
    exchange.respond(response);
}
Also used : Response(org.eclipse.californium.core.coap.Response) Request(org.eclipse.californium.core.coap.Request) CBORObject(com.upokecenter.cbor.CBORObject)

Example 17 with CBORObject

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

the class RequestStatistic method toCbor.

/**
 * Convert history list into CBOR format.
 *
 * @param history history list.
 * @return CBOR content
 */
public byte[] toCbor(List<RequestInformation> history, int maxPayloadLength) {
    CBORObject list = CBORObject.NewArray();
    CBORObject map = CBORObject.NewMap();
    map.set("systemstart", CBORObject.FromObject(START_TIME));
    list.Add(map);
    byte[] response = list.EncodeToBytes();
    for (RequestInformation entry : history) {
        map = CBORObject.NewMap();
        map.set("rid", CBORObject.FromObject(entry.requestId));
        map.set("time", CBORObject.FromObject(entry.requestTime));
        if (entry.sourceAddress != null) {
            map.set("ep", CBORObject.FromObject(entry.sourceAddress));
            map.set("port", CBORObject.FromObject(entry.sourcePort));
        }
        list.Add(map);
        byte[] payload = list.EncodeToBytes();
        if (payload.length > maxPayloadLength) {
            break;
        }
        response = payload;
    }
    return response;
}
Also used : CBORObject(com.upokecenter.cbor.CBORObject)

Example 18 with CBORObject

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

the class ResponseDecryptor method decrypt.

/**
 * Decrypt the response.
 *
 * @param db the context database used
 * @param response the response
 * @param requestSequenceNr sequence number (Partial IV) from the request
 *            (if encrypting a response)
 *
 * @return the decrypted response
 *
 * @throws OSException when decryption fails
 */
public static Response decrypt(OSCoreCtxDB db, Response response, int requestSequenceNr) throws OSException {
    discardEOptions(response);
    byte[] protectedData = response.getPayload();
    Encrypt0Message enc = null;
    Token token = response.getToken();
    OSCoreCtx ctx = null;
    OptionSet uOptions = response.getOptions();
    if (token != null) {
        ctx = db.getContextByToken(token);
        if (ctx == null) {
            LOGGER.error(ErrorDescriptions.TOKEN_INVALID);
            throw new OSException(ErrorDescriptions.TOKEN_INVALID);
        }
        enc = decompression(protectedData, response);
    } else {
        LOGGER.error(ErrorDescriptions.TOKEN_NULL);
        throw new OSException(ErrorDescriptions.TOKEN_NULL);
    }
    // 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 ongoing
    try {
        ctx = ContextRederivation.incomingResponse(db, ctx, contextID);
    } catch (OSException e) {
        LOGGER.error(ErrorDescriptions.CONTEXT_REGENERATION_FAILED);
        throw new OSException(ErrorDescriptions.CONTEXT_REGENERATION_FAILED);
    }
    // Check if parsing of response plaintext succeeds
    try {
        byte[] plaintext = decryptAndDecode(enc, response, ctx, requestSequenceNr);
        DatagramReader reader = new DatagramReader(new ByteArrayInputStream(plaintext));
        response = OptionJuggle.setRealCodeResponse(response, CoAP.ResponseCode.valueOf(reader.read(CoAP.MessageFormat.CODE_BITS)));
        // resets option so eOptions gets priority during parse
        response.setOptions(EMPTY);
        new UdpDataParser().parseOptionsAndPayload(reader, response);
    } catch (Exception e) {
        LOGGER.error(ErrorDescriptions.DECRYPTION_FAILED);
        throw new OSException(ErrorDescriptions.DECRYPTION_FAILED);
    }
    OptionSet eOptions = response.getOptions();
    eOptions = OptionJuggle.merge(eOptions, uOptions);
    response.setOptions(eOptions);
    // If it has Observe it will be removed after cancellation elsewhere
    if (response.getOptions().hasObserve() == false) {
        db.removeToken(token);
    }
    // Set information about the OSCORE context used in the endpoint context of this response
    OSCoreEndpointContextInfo.receivingResponse(ctx, response);
    return response;
}
Also used : Encrypt0Message(org.eclipse.californium.cose.Encrypt0Message) UdpDataParser(org.eclipse.californium.core.network.serialization.UdpDataParser) ByteArrayInputStream(java.io.ByteArrayInputStream) Token(org.eclipse.californium.core.coap.Token) DatagramReader(org.eclipse.californium.elements.util.DatagramReader) OptionSet(org.eclipse.californium.core.coap.OptionSet) CBORObject(com.upokecenter.cbor.CBORObject)

Example 19 with CBORObject

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

the class OSSerializer method serializeAAD.

/**
 * Prepare the additional authenticated data of a message.
 *
 * Note that for the request* parameters they must contain the value of what was in
 * a request. Either this actual request or the request associated to this response.
 *
 * external_aad = [ ver : uint, alg : int, request_kid : bstr, request_piv :
 * bstr, options : bstr]
 *
 * @param version the CoAP version number
 * @param algorithm AEAD algorithm
 * @param requestSeq the sequence number (request PIV)
 * @param requestSenderId sender ID (request KID)
 * @param options the option set
 * @return byte array with AAD
 */
public static byte[] serializeAAD(int version, AlgorithmID algorithm, int requestSeq, byte[] requestSenderId, OptionSet options) {
    if (version == CoAP.VERSION) {
        if (requestSeq > -1) {
            if (algorithm != null) {
                if (options != null) {
                    CBORObject algorithms = CBORObject.NewArray();
                    algorithms.Add(algorithm.AsCBOR());
                    CBORObject aad = CBORObject.NewArray();
                    aad.Add(version);
                    aad.Add(algorithms);
                    aad.Add(requestSenderId);
                    aad.Add(processPartialIV(requestSeq));
                    // I-class options (currently none)
                    aad.Add(CBORObject.FromObject(Bytes.EMPTY));
                    return aad.EncodeToBytes();
                } else {
                    LOGGER.error(ErrorDescriptions.OPTIONSET_NULL);
                    throw new NullPointerException(ErrorDescriptions.OPTIONSET_NULL);
                }
            } else {
                LOGGER.error(ErrorDescriptions.ALGORITHM_NOT_DEFINED);
                throw new NullPointerException(ErrorDescriptions.ALGORITHM_NOT_DEFINED);
            }
        } else {
            LOGGER.error(ErrorDescriptions.SEQ_NBR_INVALID);
            throw new IllegalArgumentException(ErrorDescriptions.SEQ_NBR_INVALID);
        }
    } else {
        LOGGER.error(ErrorDescriptions.WRONG_VERSION_NBR);
        throw new IllegalArgumentException(ErrorDescriptions.WRONG_VERSION_NBR);
    }
}
Also used : CBORObject(com.upokecenter.cbor.CBORObject)

Example 20 with CBORObject

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

the class EncryptCommon method AES_CCM_Encrypt.

private void AES_CCM_Encrypt(AlgorithmID alg, byte[] rgbKey) throws CoseException, IllegalStateException {
    SecureRandom random = new SecureRandom();
    // validate key
    if (rgbKey.length != alg.getKeySize() / Byte.SIZE) {
        throw new CoseException("Key Size is incorrect");
    }
    // obtain and validate iv
    CBORObject iv = findAttribute(HeaderKeys.IV);
    int ivLen = ivLength(alg);
    if (iv == null) {
        byte[] tmp = new byte[ivLen];
        random.nextBytes(tmp);
        iv = CBORObject.FromObject(tmp);
        addAttribute(HeaderKeys.IV, iv, Attribute.UNPROTECTED);
    } else {
        if (iv.getType() != CBORType.ByteString) {
            throw new CoseException("IV is incorreclty formed.");
        }
        if (iv.GetByteString().length > ivLen) {
            throw new CoseException("IV is too long.");
        }
    }
    // Modified to use the full AAD here rather than just the external AAD
    // Tag length (last parameter) was also included
    byte[] aad = getAADBytes();
    try {
        rgbEncrypt = CCMBlockCipher.encrypt(new SecretKeySpec(rgbKey, "AES"), iv.GetByteString(), aad, GetContent(), alg.getTagSize() / Byte.SIZE);
    } catch (NoSuchAlgorithmException ex) {
        throw new CoseException("Algorithm not supported", ex);
    } catch (Exception ex) {
        throw new CoseException("Encryption failure", ex);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) 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