LoginSignup
7
5

More than 5 years have passed since last update.

KotlinでHMAC

Last updated at Posted at 2018-01-05

kotlin_800x320.png

Kotlin で HMAC を使った暗号化をする方法をメモ. その他 Kotlin での各種暗号化は phxql/kotin-crypto-example にサンプルがあります.

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and

/**
 * Hmac by Kotlin
 */
fun main(args: Array<String>) {

    // Change algorithm as you like. ex. "HmacSHA1", "HmacMD5", etc
    val algorithm = "HmacSHA256"
    val key = "Secret Key"
    val text = "Encryption Target"

    // Encryption
    val keySpec = SecretKeySpec(key.toByteArray(), algorithm)
    val mac = Mac.getInstance(algorithm)
    mac.init(keySpec)
    val sign = mac.doFinal(text.toByteArray())
            .joinToString("") { String.format("%02x", it and 255.toByte()) }

    // 6bad2e332a94882be27d946b5fab39acd6be6fd64c6a52a27d77422daf36a6fd
    println(sign)
}
7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5