Kotlin hashids hash function

Overview

Hashids.kt

A Kotlin class to generate YouTube-like hashes from one or many numbers.

Ported from Java Hashids.java by fanweixiao (is port of javascript hashids.js by Ivan Akimov)

What is it?

Hashids (Hash ID's) creates short, unique, decryptable hashes from unsigned (long) integers.

This algorithm tries to satisfy the following requirements:

  1. Hashes must be unique and decryptable.
  2. They should be able to contain more than one integer (so you can use them in complex or clustered systems).
  3. You should be able to specify minimum hash length.
  4. Hashes should not contain basic English curse words (since they are meant to appear in public places - like the URL).

Instead of showing items as 1, 2, or 3, you could show them as U6dc, u87U, and HMou. You don't have to store these hashes in the database, but can encrypt + decrypt on the fly.

All (long) integers need to be greater than or equal to zero.

Usage

Import the package

import org.hashids;

Encrypting one number

You must pass a unique salt string so your hashes differ from everyone. I use "this is my salt" as an example.

val hashids = Hashids("this is my salt")
val hash: String = hashids.encode(12345)

hash is now going to be: NkK9

Decrypting

Notice: during decryption, the same salt value has to be used:

val hashids = Hashids("this is my salt")
val numbers: LongArray = hashids.decode("NkK9")
val numver: Int = numbers[0]

numbers is now going to be: [12345] number is: 12345

Decrypting with different salt

Decryption will not work if salt is changed:

val hashids = Hashids("this is my pepper")
val numbers: LongArray = hashids.decode("NkK9")

numbers is now going to be: []

Encrypting several numbers

val hashids = Hashids("this is my salt")
val hash: String = hashids.encode(683L, 94108L, 123L, 5L)

hash is now going to be: aBMswoO2UB3Sj

Decrypting is done the same way

val hashids = Hashids("this is my salt")
val numbers: String = hashids.decode("aBMswoO2UB3Sj")

numbers is now going to be: [683, 94108, 123, 5]

Encrypting and specifying minimum hash length

Here we encode integer 1, and set the minimum hash length to 8 (by default it's 0 -- meaning hashes will be the shortest possible length).

val hashids = Hashids("this is my salt", 8)
val hash: String = hashids.encode(1)

hash is now going to be: gB0NV05e

Decrypting

val hashids = Hashids("this is my salt", 8)
val numbers: String = hashids.decode("gB0NV05e")

numbers is now going to be: [1]

Specifying custom hash alphabet

Let's set the alphabet that consist of only four letters: "0123456789abcdef"

val hashids = Hashids("this is my salt", 0, "0123456789abcdef")
val hash: String = hashids.encode(1234567)

hash is now going to be: b332db5

Repeating numbers

val hashids = Hashids("this is my salt")
val hash: String = hashids.encode(5, 5, 5, 5);

You don't see any repeating patterns that might show there's 4 identical numbers in the hash: 1Wc8cwcE

Same with incremented numbers:

val hashids = Hashids("this is my salt")
val hash: String = hashids.encode(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

hash will be: kRHnurhptKcjIDTWC3sx

Incrementing number hashes:

val hashids = Hashids("this is my salt")
val hash1: String = hashids.encode(1) /* NV */
val hash2: String = hashids.encode(2) /* 6m */
val hash3: String = hashids.encode(3) /* yD */
val hash4: String = hashids.encode(4) /* 2l */
val hash5: String = hashids.encode(5) /* rD */

Contact

Follow me @leprosus, @IvanAkimov, @fanweixiao, @spuklo

License

MIT License. See the LICENSE file.

You might also like...
Dagger Hilt, MVP Moxy, Retrofit, Kotlin coroutine, Sealed class

Dagger Hilt, MVP Moxy, Retrofit, Kotlin coroutine, Sealed class

Item Helper For Kotlin

Item Helper For Kotlin

kotlin mvvm+dataBinding+retrofit2+Arouter等BaseActivity、BaseFragment、BaseDialogFragment基类封装
kotlin mvvm+dataBinding+retrofit2+Arouter等BaseActivity、BaseFragment、BaseDialogFragment基类封装

kotlin-mvvm kotlin mvvm+dataBinding+retrofit2+ARouter等BaseActivity、BaseFragment、BaseDialogFragment基类封装 Android开发项目基本使用框架,封装了各类组件,在基类实现了沉浸式状态栏,可以自己更改颜色

 Bar Service Kotlin Client
Bar Service Kotlin Client

A simple starter service client written in Kotlin against generated models (protos)A simple starter service client written in Kotlin against generated models (protos)

Kotlin validation with a focus on readability
Kotlin validation with a focus on readability

kommodus Kotlin validation with a focus on readability import com.github.kommodus.constraints.* import com.github.kommodus.Validation data class Test

Kotlin to Dart compiler
Kotlin to Dart compiler

Dotlin is a Kotlin to Dart compiler. The aim is to integrate Kotlin as a language into the Dart ecosystem, combing best of both worlds: The Kotlin lan

Modern Kotlin version of com.example.semitop7.FireTVStyle keyboard

ftv-style-keyboard Modern Kotlin version of com.example.semitop7.FireTVStyle keyboard Manual activation on FireTV via adb shell: adb shell ime enable

A Kotlin-based testing/scraping/parsing library providing the ability to analyze and extract data from HTML
A Kotlin-based testing/scraping/parsing library providing the ability to analyze and extract data from HTML

A Kotlin-based testing/scraping/parsing library providing the ability to analyze and extract data from HTML (server & client-side rendered). It places particular emphasis on ease of use and a high level of readability by providing an intuitive DSL. It aims to be a testing lib, but can also be used to scrape websites in a convenient fashion.

PubSub - 使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus

PubSub 使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus 下载 将它添加到项目的

Comments
  • Adding gradle build, tests and re-writing the implementation in more idiomatic Kotlin

    Adding gradle build, tests and re-writing the implementation in more idiomatic Kotlin

    Added a gradle build and some tests which I've copied from Java implementation of Hashids. Gradle build creates a jar which can be published co Maven Central etc., to enable easy use of the implementation.

    opened by spuklo 0
  • 导入之后报错,更改后的

    导入之后报错,更改后的

    
    /**
     * @Author: iLvc
     * @Date:Create in 14:23 2017/8/25
     * @Description:
     */
    import java.util.ArrayList
    import java.util.regex.Pattern
    
    /**
     * Hashids developed to generate short hashes from numbers (like YouTube).
     * Can be used as forgotten password hashes, invitation codes, store shard numbers.
     * This is implementation of http://hashids.org
     *
     * @author leprosus <[email protected]>
     * @license MIT
     */
    public class Hashids(salt: String = "", length: Int = 0, alphabet: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") {
        private val min: Int = 16
        private val sepsDiv: Double = 3.5
        private val guardDiv: Int = 12
    
        private var seps: String = "cfhistuCFHISTU"
        private var guards: String? = null
    
        private var salt: String
        private var length: Int
        private var alphabet: String
    
        init {
            this.salt = salt
            this.length = if (length > 0) length else 0
            this.alphabet = alphabet.unique()
    
            if (this.alphabet.length < min)
                throw IllegalArgumentException("Alphabet must contain at least " + min + " unique characters")
    
            /**
             * seps should contain only characters present in alphabet;
             * alphabet should not contains seps
             */
            val sepsLength = seps.length - 1
            for (index in 0..sepsLength) {
                val position = this.alphabet.indexOf(seps.elementAt(index))
    
                if (position == -1) {
                    seps = seps.substring(0, index) + " " + seps.substring(index + 1)
                } else {
                    this.alphabet = this.alphabet.substring(0, position) + " " + this.alphabet.substring(position + 1)
                }
            }
            this.alphabet = this.alphabet.replace("\\s+".toRegex(), "")
            seps = seps.replace("\\s+".toRegex(), "")
    
            seps = consistentShuffle(seps, this.salt)
    
            if ((seps == "") || ((this.alphabet.length / seps.length) > sepsDiv)) {
                var sepsCount = getCount(this.alphabet.length, sepsDiv)
    
                if (sepsCount == 1)
                    sepsCount++
    
                if (sepsCount > seps.length) {
                    val diff = sepsCount - seps.length
                    seps += this.alphabet.substring(0, diff)
                    this.alphabet = this.alphabet.substring(diff)
                } else {
                    seps = seps.substring(0, sepsCount)
                }
            }
    
            this.alphabet = this.consistentShuffle(this.alphabet, this.salt)
    
            val guardCount = getCount(this.alphabet.length, guardDiv)
    
            if (this.alphabet.length < 3) {
                guards = seps.substring(0, guardCount)
                seps = seps.substring(guardCount)
            } else {
                guards = this.alphabet.substring(0, guardCount)
                this.alphabet = this.alphabet.substring(guardCount)
            }
        }
    
        /**
         * Encrypt numbers to string
         *
         * @param numbers the numbers to encrypt
         * @return The encrypt string
         */
        fun encode(vararg numbers: Long): String {
            if (numbers.size == 0)
                return ""
    
            for (number in numbers)
                if (number > 9007199254740992)
                    throw IllegalArgumentException("Number can not be greater than 9007199254740992L")
    
            var numberHashInt: Int = 0
            for (i in numbers.indices)
                numberHashInt += (numbers[i] % (i + 100)).toInt()
    
            var alphabet = this.alphabet
            val retInt = alphabet.toCharArray()[numberHashInt % alphabet.length]
    
            var num: Long
            var sepsIndex: Int
            var guardIndex: Int
            var buffer: String
            var retString = retInt + ""
            var guard: Char
    
    
            for (i in numbers.indices) {
                num = numbers[i]
                buffer = retInt + salt + alphabet
    
                alphabet = consistentShuffle(alphabet, buffer.substring(0, alphabet.length))
                val last = hash(num, alphabet)
    
                retString += last
    
                if (i + 1 < numbers.size) {
                    num %= (last.toCharArray()[0].toInt() + i)
                    sepsIndex = (num % seps.length).toInt()
                    retString += seps.toCharArray()[sepsIndex]
                }
            }
    
            if (retString.length < length) {
                guardIndex = (numberHashInt  + (retString.toCharArray()[0]).toInt())    % guards!!.length
                guard = guards!!.toCharArray()[guardIndex]
    
                retString = guard + retString
    
                if (retString.length < length) {
                    guardIndex = (numberHashInt + retString.toCharArray()[2].toInt()) % guards!!.length
                    guard = guards!!.toCharArray()[guardIndex]
    
                    retString += guard
                }
            }
    
            val halfLength = alphabet.length / 2
            while (retString.length < length) {
                alphabet = consistentShuffle(alphabet, alphabet)
                retString = alphabet.substring(halfLength) + retString + alphabet.substring(0, halfLength)
                val excess = retString.length - length
                if (excess > 0) {
                    val position = excess / 2
                    retString = retString.substring(position, position + length)
                }
            }
    
            return retString
        }
    
        /**
         * Decrypt string to numbers
         *
         * @param hash the encrypt string
         * @return Decrypted numbers
         */
        fun decode(hash: String): LongArray {
            if (hash == "")
                return longArrayOf()
    
            var alphabet = alphabet
            val retArray = ArrayList<Long>()
    
            var i = 0
            val regexp = "[" + guards + "]"
            var hashBreakdown = hash.replace(regexp.toRegex(), " ")
            var hashArray = hashBreakdown.split(" ")
    
            if (hashArray.size == 3 || hashArray.size == 2) {
                i = 1
            }
    
            hashBreakdown = hashArray[i]
    
            val lottery = hashBreakdown.toCharArray()[0]
    
            hashBreakdown = hashBreakdown.substring(1)
            hashBreakdown = hashBreakdown.replace("[" + seps + "]".toRegex(), " ")
            hashArray = hashBreakdown.split(" ")
    
            var buffer: String
            for (subHash in hashArray) {
                buffer = lottery + salt + alphabet
                alphabet = consistentShuffle(alphabet, buffer.substring(0, alphabet.length))
               // retArray.add(unhash(subHash, alphabet))
                unhash(subHash, alphabet)?.let { retArray.add(it) }
            }
    
            var arr = LongArray(retArray.size)
            for (index in retArray.indices) {
                arr[index] = retArray.get(index)
            }
    
            if (encode(*arr) != hash) {
                arr = LongArray(0)
            }
    
            return arr
        }
    
        /**
         * Encrypt hexa to string
         *
         * @param hexa the hexa to encrypt
         * @return The encrypt string
         */
        fun encodeHex(hexa: String): String {
            if (!hexa.matches("^[0-9a-fA-F]+$".toRegex()))
                return ""
    
            val matched = ArrayList<Long>()
            val matcher = Pattern.compile("[\\w\\W]{1,12}").matcher(hexa)
    
            while (matcher.find())
                matched.add(java.lang.Long.parseLong("1" + matcher.group(), 16))
    
            val result = LongArray(matched.size)
            for (i in matched.indices) result[i] = matched.get(i)
    
            return encode(*result)
        }
    
        /**
         * Decrypt string to numbers
         *
         * @param hash the encrypt string
         * @return Decrypted numbers
         */
        fun decodeHex(hash: String): String {
            var result = ""
            val numbers = decode(hash)
    
            for (number in numbers) {
                result += java.lang.Long.toHexString(number).substring(1)
            }
    
            return result
        }
    
    
        private fun getCount(length: Int, div: Double): Int = Math.ceil(length.toDouble() / div.toDouble()).toInt()
    
        private fun getCount(length: Int, div: Int): Int = getCount(length, div.toDouble())
    
        private fun consistentShuffle(alphabet: String, salt: String): String {
            if (salt.length <= 0)
                return alphabet
    
            var shuffled = alphabet
    
            val saltArray = salt.toCharArray()
            val saltLength = salt.length
            var integer: Int
            var j: Int
            var temp: Char
    
            var i = shuffled.length - 1
            var v = 0
            var p = 0
    
            while (i > 0) {
                v %= saltLength
                integer = saltArray[v].toInt()
                p += integer
                j = (integer + v + p) % i
    
                temp = shuffled.elementAt(j)
                shuffled = shuffled.substring(0, j) + shuffled.elementAt(i) + shuffled.substring(j + 1)
                shuffled = shuffled.substring(0, i) + temp + shuffled.substring(i + 1)
    
                i--
                v++
            }
    
            return shuffled
        }
    
        private fun hash(input: Long, alphabet: String): String {
            var current = input
            var hash = ""
            val length = alphabet.length
            val array = alphabet.toCharArray()
    
            do {
                hash = array[(current % length.toLong()).toInt()] + hash
                current /= length
            } while (current > 0)
    
            return hash
        }
    
        private fun unhash(input: String, alphabet: String): Long? {
            var number: Long = 0
            var position: Long
            val inputArray = input.toCharArray()
            val length = input.length - 1
    
            for (i in 0..length) {
                position = alphabet.indexOf(inputArray[i]).toLong()
                number += (position.toDouble() * Math.pow(alphabet.length.toDouble(), (input.length - i - 1).toDouble())).toLong()
            }
    
            return number
        }
    
        fun getVersion(): String {
            return "1.0.0"
        }
    
        fun String.unique(): String {
            var unique = ""
            val length = this.length - 1
    
            for (index in 0..length) {
                var current: String = "" + this.elementAt(index)
    
                if (!unique.contains(current) && current != " ")
                    unique += current
            }
    
            return unique
        }
    }
    
    
    
    opened by ilvc 0
  • java.lang.ArrayIndexOutOfBoundsException

    java.lang.ArrayIndexOutOfBoundsException

    Hi, I'm getting this error:

    java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
            at org.Hashids.guardIndex(Hashids.kt:88)
            at org.Hashids.addGuardsIfNecessary(Hashids.kt:186)
            at org.Hashids.encode(Hashids.kt:58)
    

    Here is the code I which cause this issue:

    val hashids = Hashids("Turbo Quiz, c'est fun !", 3)
    val questionId = hashids.encode(0)
    

    It works with a minimum length of 0, 1 and 2, but from 3 it raise this error

    Edit: It seems that it occurs specifically when I'm trying to encode 0

    opened by justin-mottier 0
Owner
Denis Korolev
Denis Korolev
Remove the dependency of compiled kotlin on kotlin-stdlib

Dekotlinify This project aims to take compiled Kotlin Java bytecode (compiled by the standard Kotlin compiler) and remove all references to the Kotlin

Joseph Burton 10 Nov 29, 2022
gRPC and protocol buffers for Android, Kotlin, and Java.

Wire “A man got to have a code!” - Omar Little See the project website for documentation and APIs. As our teams and programs grow, the variety and vol

Square 3.9k Dec 31, 2022
A DSL to handle soft keyboard visibility change event written in Kotlin.

About A DSL to handle soft keyboard visibility change event written in Kotlin. How to use? Step 1. Add it in your root build.gradle at the end of repo

Vinícius Oliveira 17 Jan 7, 2023
Kotlin matrix class which supports determinant, inverse matrix, matmul, etc.

Kotrix is a set of classes that helps people dealing with linear algebra in Kotlin.

Kanguk Lee 5 Dec 8, 2022
Fuzzy string matching for Kotlin (JVM, native, JS, Web Assembly) - port of Fuzzy Wuzzy Python lib

FuzzyWuzzy-Kotlin Fuzzy string matching for Kotlin (JVM, iOS) - fork of the Java fork of of Fuzzy Wuzzy Python lib. For use in on JVM, Android, or Kot

WillowTree, LLC 54 Nov 8, 2022
🐫🐍🍢🅿 Multiplatform Kotlin library to convert strings between various case formats including Camel Case, Snake Case, Pascal Case and Kebab Case

KaseChange Multiplatform Kotlin library to convert strings between various case formats Supported Case Formats SCREAMING_SNAKE_CASE snake_case PascalC

PearX Team 67 Dec 30, 2022
Multiplaform kotlin library for calculating text differences. Based on java-diff-utils, supports JVM, JS and native targets.

kotlin-multiplatform-diff This is a port of java-diff-utils to kotlin with multiplatform support. All credit for the implementation goes to original a

Peter Trifanov 51 Jan 3, 2023
Multi-module, Kotlin, MVI, Compose, Hilt, Navigation Component, Use-cases, Room, Retrofit

Work in progress Multi-module demo app that gets data from dota2 api. API https://docs.opendota.com/ Players by rank (GET) https://api.opendota.com/ap

Mitch Tabian 321 Dec 27, 2022
recompose is a tool for converting Android layouts in XML to Kotlin code using Jetpack Compose.

recompose is a tool for converting Android layouts in XML to Kotlin code using Jetpack Compose.

Sebastian Kaspari 565 Jan 2, 2023
Markdown renderer for Kotlin Compose Multiplatform (Android, Desktop)

Markdown renderer for Kotlin Compose Multiplatform (Android, Desktop)

Mike Penz 129 Jan 1, 2023