All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.seanyinx.wing.security.hash.HMACHashAlgorithm Maven / Gradle / Ivy

The newest version!
package com.github.seanyinx.wing.security.hash;

import com.github.seanyinx.wing.security.exceptions.WingSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HMACHashAlgorithm implements HashAlgorithm {

  private static final String HMAC_SHA512 = "HmacSHA512";
  private final byte[] key;

  public HMACHashAlgorithm(String key) {
    this.key = key.getBytes();
  }

  @Override
  public String hash(String plaintext) {
    return hash(key, plaintext);
  }

  @Override
  public String hash(byte[] key, String plaintext) {
    try {
      SecretKeySpec secretKeySpec = new SecretKeySpec(key, HMAC_SHA512);
      Mac mac = Mac.getInstance(HMAC_SHA512);
      mac.init(secretKeySpec);
      return Base64.getEncoder().encodeToString(mac.doFinal(plaintext.getBytes()));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
      throw new WingSecurityException("Failed to calculate HMAC", e);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy