package com.za.common.util

import android.util.Base64
import java.nio.charset.StandardCharsets
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

/**
 * @author DoggieX
 * @create 2021/3/22 16:17
 * @mail coldpuppy@163.com
 */
object Tools {
    /**
     * @param text      要签名的文本
     * @param secretKey 阿里云MQ secretKey
     * @return 加密后的字符串
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
    @Throws(InvalidKeyException::class, NoSuchAlgorithmException::class)
    fun macSignature(text: String, secretKey: String): String {
        val charset = StandardCharsets.UTF_8
        val algorithm = "HmacSHA1"
        val mac = Mac.getInstance(algorithm)
        mac.init(SecretKeySpec(secretKey.toByteArray(charset), algorithm))
        val bytes = mac.doFinal(text.toByteArray(charset))
        // android的base64编码注意换行符情况, 使用NO_WRAP
        return String(Base64.encode(bytes, Base64.NO_WRAP), charset)
    }
}
