Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
37977 aman 1
package com.spice.profitmandi.web.util;
2
 
3
import java.nio.charset.StandardCharsets;
4
import java.security.GeneralSecurityException;
5
import java.util.Base64;
6
 
7
import javax.crypto.Mac;
8
import javax.crypto.spec.SecretKeySpec;
9
 
10
/**
11
 * Short-lived pass that lets Disha (chat.smartdukaan.com) open one store for one RBM, so the
12
 * shared key (disha.rbm.key) never reaches the browser. Must match Disha's v5/rbm_token.py:
13
 * <pre>
14
 *   token   = "v1." + b64url(payload) + "." + b64url(HMAC-SHA256(key, payload))
15
 *   payload = STORE + "|" + rbmEmail + "|" + expiresAtUnixSeconds       (UTF-8)
16
 * </pre>
17
 * STORE is trimmed and upper-cased; "" makes a list-only pass. b64url is URL-safe, no padding.
18
 */
19
public final class DishaRbmToken {
20
 
21
    public static final String VERSION = "v1";
22
 
23
    private DishaRbmToken() {
24
    }
25
 
26
    public static String mint(String key, String store, String rbmUser, long expiresAt) {
27
        if (key == null || key.trim().isEmpty()) {
28
            return "";
29
        }
30
        String payload = (store == null ? "" : store.trim().toUpperCase()) + "|"
31
                + (rbmUser == null ? "" : rbmUser.trim()) + "|" + expiresAt;
32
        byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8);
33
        try {
34
            Mac mac = Mac.getInstance("HmacSHA256");
35
            mac.init(new SecretKeySpec(key.trim().getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
36
            byte[] signature = mac.doFinal(payloadBytes);
37
            Base64.Encoder b64 = Base64.getUrlEncoder().withoutPadding();
38
            return VERSION + "." + b64.encodeToString(payloadBytes) + "." + b64.encodeToString(signature);
39
        } catch (GeneralSecurityException e) {
40
            throw new IllegalStateException("HmacSHA256 is not available in this JVM", e);
41
        }
42
    }
43
}