001// -------------------------------------------------------------------------------- 002// Copyright 2002-2026 Echo Three, LLC 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// -------------------------------------------------------------------------------- 016 017package com.echothree.util.server.persistence; 018 019import com.echothree.util.common.exception.PersistenceEncryptionException; 020import com.google.common.io.BaseEncoding; 021import java.nio.charset.StandardCharsets; 022import java.security.InvalidKeyException; 023import java.security.NoSuchAlgorithmException; 024import javax.crypto.Mac; 025import javax.enterprise.context.ApplicationScoped; 026import javax.inject.Inject; 027 028@ApplicationScoped 029public class HmacSha256Utils 030 implements MacUtils { 031 032 private static final String HMAC_256_ALGORITHM = "HmacSHA256"; 033 private static final int HMAC_256_KEYSIZE = 256; 034 035 @Inject 036 EncryptionUtils encryptionUtils; 037 038 protected HmacSha256Utils() { 039 super(); 040 } 041 042 @Override 043 public String hash(BaseFactory<?, ?> baseFactory, final String value) { 044 try { 045 var secretKey = encryptionUtils.getEntityEncryptionKey(HMAC_256_ALGORITHM, HMAC_256_KEYSIZE, baseFactory, 046 EncryptionUtils.EntityEncryptionKeyTypes.HMAC_SHA256); 047 var hmac = Mac.getInstance(HMAC_256_ALGORITHM); 048 049 hmac.init(secretKey); 050 051 return BaseEncoding.base64().encode(hmac.doFinal(value.getBytes(StandardCharsets.UTF_8))); 052 } catch (NoSuchAlgorithmException | InvalidKeyException e) { 053 throw new PersistenceEncryptionException(e); 054 } 055 } 056 057}