package com.riaektiv.crypto.hash

import org.apache.commons.codec.binary.Hex
import org.bouncycastle.crypto.digests.SHA3Digest
import org.bouncycastle.crypto.macs.HMac
import org.bouncycastle.crypto.params.KeyParameter
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.UnsupportedEncodingException

/**
 * Coding With Passion Since 1991
 * Created: 7/10/2016, 6:35 PM Eastern Time
 * @author Sergey Chuykov
 */
class HMaxTest {

    internal val KEY = "7583CA8BE5DD"

    fun hmac(message: String, key: String): String {
        try {
            val m = HMac(SHA3Digest(224))
            m.init(KeyParameter(key.toByteArray(charset("UTF-8"))))
            val bytes = message.toByteArray(charset("UTF-8"))
            m.update(bytes, 0, bytes.size)
            val mac = ByteArray(m.macSize)
            m.doFinal(mac, 0)
            return Hex.encodeHexString(mac)
        } catch (e: UnsupportedEncodingException) {
            throw IllegalStateException(e)
        }
    }

    @Test
    fun test() {
        val sign = hmac("1449450180000", KEY)
        assertTrue(sign.startsWith("67fa132"))
    }

}