001/**
002 *
003 * Copyright 2017 Paul Schaub
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.omemo.element;
018
019import java.util.ArrayList;
020import java.util.List;
021
022import org.jivesoftware.smack.packet.FullyQualifiedElement;
023import org.jivesoftware.smack.packet.XmlEnvironment;
024import org.jivesoftware.smack.util.XmlStringBuilder;
025import org.jivesoftware.smack.util.stringencoder.Base64;
026
027import org.jivesoftware.smackx.omemo.util.OmemoConstants;
028
029/**
030 * Header element of the message. The header contains information about the sender and the encrypted keys for
031 * the recipients, as well as the iv element for AES.
032 */
033public abstract class OmemoHeaderElement implements FullyQualifiedElement {
034
035    public static final String ELEMENT = "header";
036    public static final String NAMESPACE = OmemoConstants.OMEMO_NAMESPACE_V_AXOLOTL;
037
038    public static final String ATTR_SID = "sid";
039    public static final String ATTR_IV = "iv";
040
041    private final int sid;
042    private final List<OmemoKeyElement> keys;
043    private final byte[] iv;
044
045    public OmemoHeaderElement(int sid, List<OmemoKeyElement> keys, byte[] iv) {
046        this.sid = sid;
047        this.keys = keys;
048        this.iv = iv;
049    }
050
051    /**
052     * Return the deviceId of the sender of the message.
053     *
054     * @return senders id
055     */
056    public int getSid() {
057        return sid;
058    }
059
060    public ArrayList<OmemoKeyElement> getKeys() {
061        return new ArrayList<>(keys);
062    }
063
064    public byte[] getIv() {
065        return iv != null ? iv.clone() : null;
066    }
067
068    @Override
069    public String getElementName() {
070        return ELEMENT;
071    }
072
073    @Override
074    public String getNamespace() {
075        return NAMESPACE;
076    }
077
078    @Override
079    public XmlStringBuilder toXML(XmlEnvironment enclosingXmlEnvironment) {
080        XmlStringBuilder sb = new XmlStringBuilder(this, enclosingXmlEnvironment);
081        sb.attribute(ATTR_SID, getSid()).rightAngleBracket();
082
083        for (OmemoKeyElement k : getKeys()) {
084            sb.append(k);
085        }
086
087        sb.openElement(ATTR_IV).append(Base64.encodeToString(getIv())).closeElement(ATTR_IV);
088
089        return sb.closeElement(this);
090    }
091
092
093}