Skip to content

Instantly share code, notes, and snippets.

@HenningCash
Created July 16, 2019 11:47
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 HenningCash/97c56daa4fd29a979b5e9b1987cc90fe to your computer and use it in GitHub Desktop.
Save HenningCash/97c56daa4fd29a979b5e9b1987cc90fe to your computer and use it in GitHub Desktop.
Kotlin UUID to Base64 and vice versa
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.util.*
fun UUID.toBase64(): ByteArray {
val byteArray = ByteBuffer.allocate(16)
.putLong(this.mostSignificantBits)
.putLong(this.leastSignificantBits)
.array()
return Base64.getEncoder().encode(byteArray)
}
fun ByteArray.toUUID(): UUID {
try {
val dec = Base64.getDecoder().decode(this)
if (dec.size != 16) {
throw IllegalArgumentException("UUIDs can only be created from 128bit")
}
val buf = ByteBuffer.allocate(16).put(dec)
return UUID(buf.getLong(0), buf.getLong(8))
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException("Invalid Base64 sequence", e)
}
}
fun UUID.toBase64String() = String(this.toBase64())
fun String.toUUID(charset: Charset = Charsets.UTF_8) = this.toByteArray(charset).toUUID()
fun main() {
val uuid = UUID.randomUUID()
println(uuid)
val enc = uuid.toBase64String()
println(enc)
val dec = enc.toUUID()
println(dec)
print(uuid == dec)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment