diff src/main/kotlin/name/blackcap/passman/Hashing.kt @ 0:a6cfdffcaa94

Initial commit, incomplete but it runs sorta.
author David Barts <n5jrn@me.com>
date Sun, 11 Sep 2022 16:11:37 -0700
parents
children 698c4a3d758d
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/main/kotlin/name/blackcap/passman/Hashing.kt	Sun Sep 11 16:11:37 2022 -0700
@@ -0,0 +1,34 @@
+package name.blackcap.passman
+
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.nio.CharBuffer
+import java.nio.charset.Charset
+import java.nio.charset.StandardCharsets
+import java.security.MessageDigest
+
+object Hashing {
+    private const val HASHING_ALGORITHM = "MD5"
+    private val CHARSET: Charset = StandardCharsets.UTF_8
+
+    fun hash(bytes: ByteBuffer): Long {
+        val md = MessageDigest.getInstance(HASHING_ALGORITHM)
+        bytes.rewind()
+        md.update(bytes)
+        return toLong(md.digest())
+    }
+
+    fun hash(bytes: ByteArray): Long =
+        hash(ByteBuffer.wrap(bytes))
+
+    fun hash(chars: CharArray): Long =
+        hash(CHARSET.encode(CharBuffer.wrap(chars)))
+
+    fun hash(string: String): Long =
+        hash(CHARSET.encode(string))
+
+    private fun toLong(hash: ByteArray): Long = ByteBuffer.wrap(hash).run {
+        order(ByteOrder.LITTLE_ENDIAN)
+        getLong(hash.size - 8)
+    }
+}
\ No newline at end of file