Giter Site home page Giter Site logo

kotlin-hashids's Introduction

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.

kotlin-hashids's People

Contributors

leprosus avatar rgmz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotlin-hashids's Issues

Creating a release tag

Hey, it would be cool if this repository had a release tag, like 1.0.0 so that it is possible to import the library via the git url for gradle as follows:

com.github.jonas-haeusler:geojson-kotlin:1.0.0

So far, for the people struggling with maven, just fork the repo and create a release yourself, worked for me :)

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

Is this still maintained?

We are planning to use this library in production.
There haven't been any commits for 3 years, we were wondering if this is still maintained.

导入之后报错,更改后的


/**
 * @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
    }
}


Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.