001/** 002 * 003 * Copyright 2020 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.stanza_content_encryption.element; 018 019import java.security.SecureRandom; 020 021import org.jivesoftware.smack.packet.NamedElement; 022import org.jivesoftware.smack.packet.XmlEnvironment; 023import org.jivesoftware.smack.util.EqualsUtil; 024import org.jivesoftware.smack.util.RandomUtil; 025import org.jivesoftware.smack.util.StringUtils; 026import org.jivesoftware.smack.util.XmlStringBuilder; 027 028public class RandomPaddingAffixElement implements NamedElement, AffixElement { 029 030 private static final int minPaddingLength = 1; 031 private static final int maxPaddingLength = 200; 032 public static final String ELEMENT = "rpad"; 033 034 private final String padding; 035 036 public RandomPaddingAffixElement(String padding) { 037 this.padding = StringUtils.escapeForXmlText( 038 StringUtils.requireNotNullNorEmpty(padding, "Value of 'rpad' MUST NOT be null nor empty.")) 039 .toString(); 040 } 041 042 public RandomPaddingAffixElement() { 043 this(StringUtils.randomString(randomPaddingLength(), new SecureRandom())); 044 } 045 046 private static int randomPaddingLength() { 047 return minPaddingLength + RandomUtil.nextSecureRandomInt(maxPaddingLength - minPaddingLength); 048 } 049 050 public String getPadding() { 051 return padding; 052 } 053 054 @Override 055 public String getElementName() { 056 return ELEMENT; 057 } 058 059 @Override 060 public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) { 061 return new XmlStringBuilder(this).rightAngleBracket() 062 .append(getPadding()) 063 .closeElement(this); 064 } 065 066 @Override 067 public boolean equals(Object obj) { 068 return EqualsUtil.equals(this, obj, (e, o) -> e.append(getPadding(), o.getPadding())); 069 } 070 071 @Override 072 public int hashCode() { 073 return getPadding().hashCode(); 074 } 075}