summaryrefslogtreecommitdiffstats
path: root/security-utils/src/main/java/com/yahoo/security/token/TokenCheckHash.java
blob: e4d9825842e92b603a83b4eaaeae2da1d8e8bebb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.token;

import java.util.Arrays;

import static com.yahoo.security.ArrayUtils.hex;

/**
 * A token check hash represents a hash derived from a token in such a way that
 * distinct "audiences" for the token compute entirely different hashes even for
 * identical token values.
 */
public record TokenCheckHash(byte[] hashBytes) {

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TokenCheckHash tokenCheckHash = (TokenCheckHash) o;
        // We don't consider token hashes secret data, so no harm in data-dependent equals()
        return Arrays.equals(hashBytes, tokenCheckHash.hashBytes);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(hashBytes);
    }

    public String toHexString() {
        return hex(hashBytes);
    }

    @Override
    public String toString() {
        return toHexString();
    }

    public static TokenCheckHash of(Token token, int nHashBytes) {
        return new TokenCheckHash(token.toDerivedBytes(nHashBytes, token.domain().checkHashContext()));
    }

    public static TokenCheckHash ofRawBytes(byte[] hashBytes) {
        return new TokenCheckHash(Arrays.copyOf(hashBytes, hashBytes.length));
    }

}