Base62Cipher.java 1.71 KB
package com.diligrp.cashier.shared.security;

public final class Base62Cipher {

    private static final char[] BASE62_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    private static final int BASE = 62;

    public static String encodeLong(long data) {
        if (data < 0) {
            throw new IllegalArgumentException("cannot be negative");
        }

        if (data == 0) {
            return String.valueOf(BASE62_CHARS[0]);
        }

        StringBuilder sb = new StringBuilder();
        while (data > 0) {
            int remainder = (int) (data % BASE);
            sb.append(BASE62_CHARS[remainder]);
            data = data / BASE;
        }

        // 反转字符串(因为取余是从低位到高位,需要反转恢复顺序)
        return sb.reverse().toString();
    }

    public static long decodeLong(String payload) {
        if (payload == null || payload.isEmpty()) {
            throw new IllegalArgumentException("Invalid base62 data");
        }

        long result = 0;
        for (char c : payload.toCharArray()) {
            if (result > (Long.MAX_VALUE - getCharIndex(c)) / BASE) {
                throw new NumberFormatException("Invalid base62 data: overflow long");
            }
            result = result * BASE + getCharIndex(c);
        }
        return result;
    }

    private static int getCharIndex(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        } else if (c >= 'a' && c <= 'z') {
            return 10 + (c - 'a');
        } else if (c >= 'A' && c <= 'Z') {
            return 36 + (c - 'A');
        } else {
            throw new IllegalArgumentException("invalid base62 data:" + c);
        }
    }
}