Skip to content

Instantly share code, notes, and snippets.

@schott12521
Last active March 5, 2018 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schott12521/e9fe3462e821166cecfba7fb8f7fea5d to your computer and use it in GitHub Desktop.
Save schott12521/e9fe3462e821166cecfba7fb8f7fea5d to your computer and use it in GitHub Desktop.
Dervice Key from Seed in Kotlin
// blake2b(n || seed, dkLen = 32)
fun deriveKeyFromSeed(seed: String, index: Int) : String {
val param = Blake2b.Param().setDigestLength(32)
val blake2b = Blake2b.Digest.newInstance(param)
val indexBytes = hexStringToByteArray(String.format("%08x", index))
blake2b.update(hexStringToByteArray(seed))
blake2b.update(indexBytes)
val output = blake2b.digest()
return byteArrayToHex(output)
}
fun byteArrayToHex(a: ByteArray): String {
val sb = StringBuilder(a.size * 2)
for (b in a)
sb.append(String.format("%02x", b))
return sb.toString()
}
fun hexStringToByteArray(s: String): ByteArray {
val len = s.length
val data = ByteArray(len / 2)
var i = 0
while (i < len) {
data[i / 2] = ((Character.digit(s[i], 16) shl 4) + Character.digit(s[i + 1], 16)).toByte()
i += 2
}
return data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment