001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package org.pgpainless.util;
006
007import javax.annotation.Nonnull;
008
009import org.bouncycastle.openpgp.PGPSessionKey;
010import org.pgpainless.algorithm.SymmetricKeyAlgorithm;
011
012/**
013 * A {@link SessionKey} is the symmetric key that is used to encrypt/decrypt an OpenPGP message.
014 * The OpenPGP message header contains a copy of the session key, encrypted for the public key of each recipient.
015 */
016public class SessionKey {
017
018    private final SymmetricKeyAlgorithm algorithm;
019    private final byte[] key;
020
021    /**
022     * Constructor to create a session key from a BC {@link PGPSessionKey} object.
023     *
024     * @param sessionKey BC session key
025     */
026    public SessionKey(@Nonnull PGPSessionKey sessionKey) {
027        this(SymmetricKeyAlgorithm.fromId(sessionKey.getAlgorithm()), sessionKey.getKey());
028    }
029
030    /**
031     * Create a session key object from an algorithm and a key.
032     *
033     * @param algorithm algorithm
034     * @param key key
035     */
036    public SessionKey(@Nonnull SymmetricKeyAlgorithm algorithm, @Nonnull byte[] key) {
037        this.algorithm = algorithm;
038        this.key = key;
039    }
040
041    /**
042     * Return the symmetric key algorithm.
043     *
044     * @return algorithm
045     */
046    public SymmetricKeyAlgorithm getAlgorithm() {
047        return algorithm;
048    }
049
050    /**
051     * Return the bytes of the key.
052     *
053     * @return key
054     */
055    public byte[] getKey() {
056        byte[] copy = new byte[key.length];
057        System.arraycopy(key, 0, copy, 0, copy.length);
058        return copy;
059    }
060}