001/*
002 * Copyright 2018 Paul Schaub.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.pgpainless.key.collection;
017
018import javax.annotation.Nonnull;
019import javax.annotation.Nullable;
020
021import org.bouncycastle.openpgp.PGPPublicKey;
022import org.bouncycastle.openpgp.PGPPublicKeyRing;
023import org.bouncycastle.openpgp.PGPSecretKeyRing;
024import org.pgpainless.key.OpenPgpV4Fingerprint;
025
026public class PGPKeyRing {
027
028    private PGPPublicKeyRing publicKeys;
029    private PGPSecretKeyRing secretKeys;
030
031    public PGPKeyRing(@Nonnull PGPPublicKeyRing publicKeys, @Nonnull PGPSecretKeyRing secretKeys) {
032
033        if (publicKeys.getPublicKey().getKeyID() != secretKeys.getPublicKey().getKeyID()) {
034            throw new IllegalArgumentException("publicKeys and secretKeys must have the same master key.");
035        }
036
037        this.publicKeys = publicKeys;
038        this.secretKeys = secretKeys;
039    }
040
041    public PGPKeyRing(@Nonnull PGPPublicKeyRing publicKeys) {
042        this.publicKeys = publicKeys;
043    }
044
045    public PGPKeyRing(@Nonnull PGPSecretKeyRing secretKeys) {
046        this.secretKeys = secretKeys;
047    }
048
049    public long getKeyId() {
050        return getMasterKey().getKeyID();
051    }
052
053    public @Nonnull PGPPublicKey getMasterKey() {
054        PGPPublicKey publicKey = hasSecretKeys() ? secretKeys.getPublicKey() : publicKeys.getPublicKey();
055        if (!publicKey.isMasterKey()) {
056            throw new IllegalStateException("Expected master key is not a master key");
057        }
058        return publicKey;
059    }
060
061    public @Nonnull OpenPgpV4Fingerprint getV4Fingerprint() {
062        return new OpenPgpV4Fingerprint(getMasterKey());
063    }
064
065    public boolean hasSecretKeys() {
066        return secretKeys != null;
067    }
068
069    public @Nullable PGPPublicKeyRing getPublicKeys() {
070        return publicKeys;
071    }
072
073    public @Nullable PGPSecretKeyRing getSecretKeys() {
074        return secretKeys;
075    }
076}