001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package sop;
006
007import java.util.Arrays;
008import java.util.regex.Matcher;
009import java.util.regex.Pattern;
010
011import sop.util.HexUtil;
012
013public class SessionKey {
014
015    private static final Pattern PATTERN = Pattern.compile("^(\\d):([0-9a-fA-F]+)$");
016
017    private final byte algorithm;
018    private final byte[] sessionKey;
019
020    public SessionKey(byte algorithm, byte[] sessionKey) {
021        this.algorithm = algorithm;
022        this.sessionKey = sessionKey;
023    }
024
025    /**
026     * Return the symmetric algorithm octet.
027     *
028     * @return algorithm id
029     */
030    public byte getAlgorithm() {
031        return algorithm;
032    }
033
034    /**
035     * Return the session key.
036     *
037     * @return session key
038     */
039    public byte[] getKey() {
040        return sessionKey;
041    }
042
043    @Override
044    public int hashCode() {
045        return getAlgorithm() * 17 + Arrays.hashCode(getKey());
046    }
047
048    @Override
049    public boolean equals(Object other) {
050        if (other == null) {
051            return false;
052        }
053        if (this == other) {
054            return true;
055        }
056        if (!(other instanceof SessionKey)) {
057            return false;
058        }
059
060        SessionKey otherKey = (SessionKey) other;
061        return getAlgorithm() == otherKey.getAlgorithm() && Arrays.equals(getKey(), otherKey.getKey());
062    }
063
064    public static SessionKey fromString(String string) {
065        Matcher matcher = PATTERN.matcher(string);
066        if (!matcher.matches()) {
067            throw new IllegalArgumentException("Provided session key does not match expected format.");
068        }
069        byte algorithm = Byte.parseByte(matcher.group(1));
070        String key = matcher.group(2);
071
072        return new SessionKey(algorithm, HexUtil.hexToBytes(key));
073    }
074
075    @Override
076    public String toString() {
077        return "" + (int) getAlgorithm() + ':' + HexUtil.bytesToHex(sessionKey);
078    }
079}