/*
 * Copyright (C) 2016 Freddy Barrera [freddy.barrera.moo(at)gmail.com.mx]
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package mx.neocs.sakila.util;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * This class util help with the cryptography.
 *
 * @author Freddy Barrera [freddy.barrera.moo(at)gmail.com.mx]
 */
public class Crypto {

    /** Constructor not accessible for create a instance using the keyword new. */
    private Crypto() {
    }

    /**
     * This method help to encode a message using hash message authentication code (HMAC) with and
     * encoded with Base64.
     * 
     * @param message the message to encoded.
     * @return message encoded.
     */
    public static String hmac(String message) {
        return hmac("The life is better when we share our knowledge.", message);
    }

    /**
     * This method help to encode a message using hash message authentication code (HMAC) and
     * encoded with Base64.
     * 
     * @param key the key for encode.
     * @param message the message to encoded.
     * @return message encoded.
     */    
    public static String hmac(final String key, final String message) {
        try {
            byte[] keyAsByte = key.getBytes(StandardCharsets.UTF_8);
            byte[] messageAsByte = message.getBytes(StandardCharsets.UTF_8);
            final Mac hMacSHA512 = Mac.getInstance("HmacSHA512");
            final Key secretKey = new SecretKeySpec(keyAsByte, "HmacSHA512");
            hMacSHA512.init(secretKey);

            return Base64.encodeBase64String(hMacSHA512.doFinal(messageAsByte));
        } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException ex) {
            throw new RuntimeException(ex);
        }
    }
}
