auth-server/src/main/java/com/stktrk/app/utils/EncryptId.java

45 lines
1.3 KiB
Java

package com.stktrk.app.utils;
import com.arcadedb.database.RID;
import jakarta.annotation.Nonnull;
import jakarta.validation.constraints.NotEmpty;
import org.hashids.Hashids;
import java.security.InvalidKeyException;
public class EncryptId {
// TODO move salt into properties
@Nonnull
private static final String SALT = "yG8kWVG0kei4wqwXGgt99AXxJWD7K2fnK4xv3BDR0M0AHchvFFCjFJK4VH1nLvm1";
@Nonnull
public static String encrypt(@Nonnull RID rid) {
return new Hashids(SALT).encode(rid.getBucketId(), rid.getPosition());
}
// TODO illegal argument exception thrown from RID - if we only allow this to come from the DB, we should be good.
@Nonnull
public static String encrypt(@NotEmpty String rid) {
RID obj = new RID(rid);
return new Hashids(SALT).encode(obj.getBucketId(), obj.getPosition());
}
@Nonnull
public static RID decrypt(@NotEmpty String hash) throws InvalidKeyException {
long[] res = new Hashids(SALT).decode(hash);
if (res == null || res.length != 2 ) {
throw new InvalidKeyException("invalid id");
}
return new RID((int) res[0], res[1]);
}
@Nonnull
private Boolean isValidRid (String rid) {
return rid.matches("#\\d+\\.\\d+");
}
}