Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ArrayIndexOutOfBoundsException from encode(long... numbers) #30

Closed
philbayer opened this issue Oct 3, 2016 · 2 comments
Closed

ArrayIndexOutOfBoundsException from encode(long... numbers) #30

philbayer opened this issue Oct 3, 2016 · 2 comments
Assignees
Labels

Comments

@philbayer
Copy link

philbayer commented Oct 3, 2016

Problem:
If the list of longs passed to the method public String encode(long... numbers) contains a negative value, it may result in a java.lang.ArrayIndexOutOfBoundsException being thrown. Here is the offending code snippet (see added inline comments.

  private String _encode(long... numbers){
    int numberHashInt = 0;
    for(int i = 0; i < numbers.length; i++){
      numberHashInt += (numbers[i] % (i+100));  // If numbers contains a negative long value then numberHashInt could be negative
    }
    String alphabet = this.alphabet;
    char ret = alphabet.toCharArray()[numberHashInt % alphabet.length()]; // if numberHashInt is negative, an ArrayIndexOutOfBoundsException will be thrown

Possible Solutions:

  1. In the method public String encode(long... numbers) replace the following line

if (number > 9007199254740992L) {

with

if (number > 9007199254740992L || number < 0) {

  1. In the method private String _encode(long... numbers) use the absolute value of the long values in numbers when computing the hash:
int numberHashInt = 0;
for(int i = 0; i < numbers.length; i++){
  numberHashInt += (Math.abs(numbers[i]) % (i+100));
}
0x3333 added a commit that referenced this issue Oct 3, 2016
@0x3333 0x3333 added the bug label Oct 3, 2016
@0x3333 0x3333 self-assigned this Oct 3, 2016
@0x3333
Copy link
Collaborator

0x3333 commented Oct 3, 2016

Fixed.

When encoding negative numbers, the result should be ""(empty string), same behaviour as the javascript implementation.

https://github.com/ivanakimov/hashids.js/blob/master/lib/hashids.js#L111-L115

@0x3333 0x3333 closed this as completed Oct 3, 2016
@0x3333
Copy link
Collaborator

0x3333 commented Oct 3, 2016

Just to make it clear, the fix has not been released. It has been fixed in HEAD.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants