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.ox;
018
019import static org.jivesoftware.smack.util.StringUtils.UNAMBIGUOUS_NUMBERS_AND_LETTERS_STRING;
020
021import java.util.regex.Pattern;
022
023/**
024 * Represents a secret key backup passphrase whose format is described in XEP-0373 §5.3.
025 *
026 * @see <a href="https://xmpp.org/extensions/xep-0373.html#backup-encryption">
027 *      XEP-0373 §5.4 Encrypting the Secret Key Backup</a>
028 */
029public class OpenPgpSecretKeyBackupPassphrase implements CharSequence {
030
031    private static final Pattern PASSPHRASE_PATTERN = Pattern.compile(
032            "^([" + UNAMBIGUOUS_NUMBERS_AND_LETTERS_STRING + "]{4}-){5}" +
033                    "[" + UNAMBIGUOUS_NUMBERS_AND_LETTERS_STRING + "]{4}$");
034
035    private final String passphrase;
036
037    public OpenPgpSecretKeyBackupPassphrase(String passphrase) {
038        if (!PASSPHRASE_PATTERN.matcher(passphrase).matches()) {
039            throw new IllegalArgumentException("Passphrase must be 24 upper case letters and numbers from the english " +
040                    "alphabet without 'O' and '0', divided into blocks of 4 and separated with dashes ('-').");
041        }
042        this.passphrase = passphrase;
043    }
044
045    @Override
046    public int length() {
047        return passphrase.length();
048    }
049
050    @Override
051    public char charAt(int i) {
052        return passphrase.charAt(i);
053    }
054
055    @Override
056    public CharSequence subSequence(int i, int i1) {
057        return passphrase.subSequence(i, i1);
058    }
059
060    @Override
061    public String toString() {
062        return passphrase;
063    }
064}