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 org.jivesoftware.smack.packet.NamedElement;
020import org.jivesoftware.smack.util.XmlStringBuilder;
021import org.jivesoftware.smack.util.stringencoder.Base64;
022
023/**
024 * Small class to collect key (byte[]), its id and whether its a preKey or not.
025 */
026public class OmemoKeyElement implements NamedElement {
027
028    public static final String NAME_KEY = "key";
029    public static final String ATTR_RID = "rid";
030    public static final String ATTR_PREKEY = "prekey";
031
032    private final byte[] data;
033    private final int id;
034    private final boolean preKey;
035
036    public OmemoKeyElement(byte[] data, int id) {
037        this.data = data;
038        this.id = id;
039        this.preKey = false;
040    }
041
042    public OmemoKeyElement(byte[] data, int id, boolean preKey) {
043        this.data = data;
044        this.id = id;
045        this.preKey = preKey;
046    }
047
048    public int getId() {
049        return this.id;
050    }
051
052    public byte[] getData() {
053        return this.data;
054    }
055
056    public boolean isPreKey() {
057        return this.preKey;
058    }
059
060    @Override
061    public String toString() {
062        return Integer.toString(id);
063    }
064
065    @Override
066    public String getElementName() {
067        return NAME_KEY;
068    }
069
070    @Override
071    public CharSequence toXML(String enclosingNamespace) {
072        XmlStringBuilder sb = new XmlStringBuilder(this);
073
074        if (isPreKey()) {
075            sb.attribute(ATTR_PREKEY, true);
076        }
077
078        sb.attribute(ATTR_RID, getId());
079        sb.rightAngleBracket();
080        sb.append(Base64.encodeToString(getData()));
081        sb.closeElement(this);
082        return sb;
083    }
084}