use of com.upokecenter.cbor.CBORObject in project californium by eclipse.
the class EncryptCommon method AES_CCM_Decrypt.
private void AES_CCM_Decrypt(AlgorithmID alg, byte[] rgbKey) throws CoseException, IllegalStateException {
// validate key
if (rgbKey.length != alg.getKeySize() / Byte.SIZE) {
throw new CoseException("Key Size is incorrect");
}
// obtain and validate IV
final int ivLen = ivLength(alg);
CBORObject iv = findAttribute(HeaderKeys.IV);
if (iv == null) {
throw new CoseException("Missing IV during decryption");
}
if (iv.getType() != CBORType.ByteString) {
throw new CoseException("IV is incorrectly formed");
}
if (iv.GetByteString().length != ivLen) {
throw new CoseException("IV size is incorrect");
}
// Modified to use the full AAD here rather than just the external AAD
// Tag length (last parameter) was also included
byte[] aad = getAADBytes();
try {
rgbContent = CCMBlockCipher.decrypt(new SecretKeySpec(rgbKey, "AES"), iv.GetByteString(), aad, getEncryptedContent(), alg.getTagSize() / Byte.SIZE);
} catch (NoSuchAlgorithmException ex) {
throw new CoseException("Algorithm not supported", ex);
} catch (InvalidKeyException ex) {
if (ex.getMessage().equals("Illegal key size")) {
throw new CoseException("Unsupported key size", ex);
}
throw new CoseException("Decryption failure", ex);
} catch (Exception ex) {
ex.printStackTrace();
throw new CoseException("Decryption failure", ex);
}
}
use of com.upokecenter.cbor.CBORObject in project californium by eclipse.
the class Message method DecodeFromBytes.
/**
* Decode a COSE message object. Use a value of {@code MessageTag.Unknown}
* to decode a generic structure with tagging. Use a specific value if
* the tagging is absent or if a known structure is passed in.
*
* @param rgbData byte stream to be decoded
* @param defaultTag assumed message type to be decoded
* @return the decoded message object
* @throws CoseException on a decode failure.
*/
public static Message DecodeFromBytes(byte[] rgbData, MessageTag defaultTag) throws CoseException {
CBORObject messageObject = CBORObject.DecodeFromBytes(rgbData);
if (messageObject.getType() != CBORType.Array)
throw new CoseException("Message is not a COSE security Message");
if (messageObject.isTagged()) {
if (messageObject.getTagCount() != 1)
throw new CoseException("Malformed message - too many tags");
if (defaultTag == MessageTag.Unknown) {
defaultTag = MessageTag.FromInt(messageObject.getMostInnerTag().ToInt32Unchecked());
} else if (defaultTag != MessageTag.FromInt(messageObject.getMostInnerTag().ToInt32Unchecked())) {
throw new CoseException("Passed in tag does not match actual tag");
}
}
Message msg;
switch(defaultTag) {
case // Unknown
Unknown:
throw new CoseException("Message was not tagged and no default tagging option given");
case Encrypt:
case MAC:
case MAC0:
case Sign1:
case Sign:
throw new CoseException("Message format not supported by this library");
case Encrypt0:
msg = new Encrypt0Message();
break;
default:
throw new CoseException("Message is not recognized as a COSE security Object");
}
msg.DecodeFromCBORObject(messageObject);
return msg;
}
use of com.upokecenter.cbor.CBORObject in project californium by eclipse.
the class Decryptor method decryptAndDecode.
/**
* Decrypts and decodes the message.
*
* @param enc the COSE structure
* @param message the message
* @param ctx the OSCore context
* @param seqByToken the sequence number
*
* @return the decrypted plaintext
*
* @throws OSException if decryption or decoding fails
*/
protected static byte[] decryptAndDecode(Encrypt0Message enc, Message message, OSCoreCtx ctx, Integer seqByToken) throws OSException {
int seq = -2;
boolean isRequest = message instanceof Request;
byte[] nonce = null;
byte[] partialIV = null;
byte[] aad = null;
if (isRequest) {
CBORObject piv = enc.findAttribute(HeaderKeys.PARTIAL_IV);
if (piv == null) {
LOGGER.error("Decryption failed: no partialIV in request");
throw new OSException(ErrorDescriptions.DECRYPTION_FAILED);
} else {
partialIV = piv.GetByteString();
partialIV = expandToIntSize(partialIV);
seq = ByteBuffer.wrap(partialIV).getInt();
// Note that the code below can throw an OSException when replays are detected
ctx.checkIncomingSeq(seq);
nonce = OSSerializer.nonceGeneration(partialIV, ctx.getRecipientId(), ctx.getCommonIV(), ctx.getIVLength());
aad = OSSerializer.serializeAAD(CoAP.VERSION, ctx.getAlg(), seq, ctx.getRecipientId(), message.getOptions());
}
} else {
if (seqByToken == null) {
LOGGER.error("Decryption failed: the arrived response is not connected to a request we sent");
throw new OSException(ErrorDescriptions.DECRYPTION_FAILED);
}
CBORObject piv = enc.findAttribute(HeaderKeys.PARTIAL_IV);
// Sequence number taken from original request
seq = seqByToken;
if (piv == null) {
// Use the partialIV that arrived in the original request (response has no partial IV)
partialIV = ByteBuffer.allocate(INTEGER_BYTES).putInt(seq).array();
nonce = OSSerializer.nonceGeneration(partialIV, ctx.getSenderId(), ctx.getCommonIV(), ctx.getIVLength());
} else {
// Since the response contains a partial IV use it for nonce calculation
partialIV = piv.GetByteString();
partialIV = expandToIntSize(partialIV);
nonce = OSSerializer.nonceGeneration(partialIV, ctx.getRecipientId(), ctx.getCommonIV(), ctx.getIVLength());
}
// Nonce calculation uses partial IV in response (if present).
// AAD calculation always uses partial IV (seq. nr.) of original request.
aad = OSSerializer.serializeAAD(CoAP.VERSION, ctx.getAlg(), seq, ctx.getSenderId(), message.getOptions());
}
byte[] plaintext = null;
byte[] key = ctx.getRecipientKey();
enc.setExternal(aad);
try {
enc.addAttribute(HeaderKeys.Algorithm, ctx.getAlg().AsCBOR(), Attribute.DO_NOT_SEND);
enc.addAttribute(HeaderKeys.IV, CBORObject.FromObject(nonce), Attribute.DO_NOT_SEND);
plaintext = enc.decrypt(key);
} catch (CoseException e) {
String details = ErrorDescriptions.DECRYPTION_FAILED + " " + e.getMessage();
LOGGER.error(details);
throw new OSException(details);
}
return plaintext;
}
use of com.upokecenter.cbor.CBORObject in project californium by eclipse.
the class ReceivetestClient method processCBOR.
public static String processCBOR(byte[] payload, String errors, boolean verbose) {
try {
StringBuilder statistic = new StringBuilder();
CBORObject element = CBORObject.DecodeFromBytes(payload);
if (verbose && element.getType() == CBORType.Array) {
// expected JSON data
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");
try {
for (CBORObject item : element.getValues()) {
if (item.getType() != CBORType.Map) {
// unexpected =>
// stop application pretty printing
statistic.setLength(0);
break;
}
CBORObject value;
if ((value = item.get("rid")) != null) {
String rid = value.AsString();
long time = item.get("time").AsNumber().ToInt64Checked();
if (rid.startsWith(REQUEST_ID_PREFIX)) {
boolean hit = errors.contains(rid);
rid = rid.substring(REQUEST_ID_PREFIX.length());
long requestTime = Long.parseLong(rid);
statistic.append("Request: ").append(format.format(requestTime));
long diff = time - requestTime;
if (-MAX_DIFF_TIME_IN_MILLIS < diff && diff < MAX_DIFF_TIME_IN_MILLIS) {
statistic.append(", received: ").append(diff).append(" ms");
} else {
statistic.append(", received: ").append(format.format(time));
}
if (hit) {
statistic.append(" * lost response!");
}
} else {
statistic.append("Request: ").append(rid);
statistic.append(", received: ").append(format.format(time));
}
if ((value = item.get("ep")) != null) {
byte[] endpoint = value.GetByteString();
int port = item.get("port").AsNumber().ToInt16Checked() & 0xffff;
statistic.append(System.lineSeparator());
String address = InetAddress.getByAddress(endpoint).getHostAddress();
if (address.contains(":")) {
address = "[" + address + "]";
}
statistic.append(" (").append(address).append(":").append(port).append(")");
}
statistic.append(System.lineSeparator());
} else {
long time = item.get("systemstart").AsNumber().ToInt64Checked();
statistic.append("Server's system start: ").append(format.format(time));
statistic.append(System.lineSeparator());
}
}
} catch (Throwable e) {
// unexpected => stop application pretty printing
statistic.setLength(0);
}
}
if (statistic.length() > 0) {
return statistic.toString();
} else {
// CBOR plain pretty printing
return element.toString();
}
} catch (CBORException e) {
// plain payload
e.printStackTrace();
return StringUtil.byteArray2Hex(payload);
}
}
use of com.upokecenter.cbor.CBORObject in project californium by eclipse.
the class Diagnose method toCbor.
public byte[] toCbor(Integer maxConnections, Integer nodeId, List<CounterStatisticManager> healths) {
CBORObject map = CBORObject.NewOrderedMap();
map.set("systemstart", CBORObject.FromObject(START_TIME));
if (nodeId != null) {
map.set("node-id", CBORObject.FromObject(nodeId));
}
if (maxConnections != null) {
map.set("max-connections", CBORObject.FromObject(maxConnections));
}
if (healths != null && !healths.isEmpty()) {
CounterStatisticManager first = healths.get(0);
long lastTransfer = ClockUtil.nanoRealtime() - first.getLastTransferTime();
map.set("since", CBORObject.FromObject(TimeUnit.NANOSECONDS.toSeconds(lastTransfer) + "s"));
int counter = 0;
for (CounterStatisticManager manager : healths) {
CBORObject group = CBORObject.NewOrderedMap();
for (String key : manager.getKeys()) {
SimpleCounterStatistic statistic = manager.getByKey(key);
if (statistic != null) {
long[] pair = statistic.getCountersPair();
CBORObject info = CBORObject.NewOrderedMap();
info.set("cur", CBORObject.FromObject(pair[0]));
info.set("all", CBORObject.FromObject(pair[1]));
group.set(key, info);
}
}
String tag = manager.getTag();
if (tag != null && !tag.isEmpty()) {
map.set(tag, group);
} else {
map.set(Integer.toString(++counter), group);
}
}
}
return map.EncodeToBytes();
}
Aggregations