001/**
002 *
003 * Copyright 2017-2019 Florian Schmaus, 2018 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.ox.element;
018
019import java.util.Date;
020import java.util.List;
021import java.util.Set;
022
023import org.jivesoftware.smack.packet.ExtensionElement;
024import org.jivesoftware.smack.util.Objects;
025import org.jivesoftware.smack.util.RandomUtil;
026import org.jivesoftware.smack.util.StringUtils;
027import org.jivesoftware.smack.util.XmlStringBuilder;
028
029import org.jxmpp.jid.Jid;
030
031/**
032 * Abstract class that bundles functionality of encrypted OpenPGP content elements ({@link CryptElement},
033 * {@link SigncryptElement}) together.
034 */
035public abstract class EncryptedOpenPgpContentElement extends OpenPgpContentElement {
036
037    public static final String ELEM_RPAD = "rpad";
038
039    private final String rpad;
040
041    protected EncryptedOpenPgpContentElement(Set<? extends Jid> to, String rpad, Date timestamp, List<ExtensionElement> payload) {
042        super(Objects.requireNonNullNorEmpty(
043                to, "Encrypted OpenPGP content elements must have at least one 'to' attribute."),
044                timestamp, payload);
045        this.rpad = Objects.requireNonNull(rpad);
046    }
047
048    protected EncryptedOpenPgpContentElement(Set<? extends Jid> to, List<ExtensionElement> payload) {
049        super(Objects.requireNonNullNorEmpty(
050                to, "Encrypted OpenPGP content elements must have at least one 'to' attribute."),
051                new Date(), payload);
052        this.rpad = createRandomPadding();
053    }
054
055    private static String createRandomPadding() {
056        int len = RandomUtil.nextSecureRandomInt(256);
057        return StringUtils.randomString(len);
058    }
059
060    @Override
061    protected void addCommonXml(XmlStringBuilder xml) {
062        super.addCommonXml(xml);
063
064        xml.openElement("rpad").escape(rpad).closeElement("rpad");
065    }
066}