Created
July 16, 2019 11:47
-
-
Save HenningCash/97c56daa4fd29a979b5e9b1987cc90fe to your computer and use it in GitHub Desktop.
Kotlin UUID to Base64 and vice versa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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