Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.util;

import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Short-lived pass that lets Disha (chat.smartdukaan.com) open one store for one RBM, so the
 * shared key (disha.rbm.key) never reaches the browser. Must match Disha's v5/rbm_token.py:
 * <pre>
 *   token   = "v1." + b64url(payload) + "." + b64url(HMAC-SHA256(key, payload))
 *   payload = STORE + "|" + rbmEmail + "|" + expiresAtUnixSeconds       (UTF-8)
 * </pre>
 * STORE is trimmed and upper-cased; "" makes a list-only pass. b64url is URL-safe, no padding.
 */
public final class DishaRbmToken {

    public static final String VERSION = "v1";

    private DishaRbmToken() {
    }

    public static String mint(String key, String store, String rbmUser, long expiresAt) {
        if (key == null || key.trim().isEmpty()) {
            return "";
        }
        String payload = (store == null ? "" : store.trim().toUpperCase()) + "|"
                + (rbmUser == null ? "" : rbmUser.trim()) + "|" + expiresAt;
        byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8);
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(key.trim().getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signature = mac.doFinal(payloadBytes);
            Base64.Encoder b64 = Base64.getUrlEncoder().withoutPadding();
            return VERSION + "." + b64.encodeToString(payloadBytes) + "." + b64.encodeToString(signature);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException("HmacSHA256 is not available in this JVM", e);
        }
    }
}