Java Signature Generator

public class Signature {
    private final String hash;
    private final String salt;

    public Signature(String hash, String salt) {
        this.hash = hash;
        this.salt = salt;
    }

    public String getHash() {
        return hash;
    }

    public String getSalt() {
        return salt;
    }
}
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;

public class SignatureGenerator {
    public Signature generate(String url, Map<String, ?> params, String secret, String salt) {
        String path = (new URL(url)).getPath();
    
        StringBuilder values = getValues(params);
        String toSign = path + values.toString() + (salt != null ? salt : "");
    
        String hmac = hmacSha256(toSign, secret);
    
        return new Signature(hmac, salt);
    }
    
    private StringBuilder getValues(Map<String, ?> obj) {
        StringBuilder values = new StringBuilder();
    
        obj.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .forEach(e -> {
                Object value = e.getValue();
    
                if (value instanceof Map || value instanceof Object[]) {
                    values.append(getValues((Map<String, ?>) value));
                    return;
                }
    
                if (value instanceof Boolean) {
                    values.append((Boolean) value ? "1" : "0");
                    return;
                }
    
                values.append(value != null ? value.toString() : "");
            });
    
        return values;
    }
    
    private String hmacSha256(String message, String secret) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(secretKeySpec);
            byte[] hash = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return Arrays.stream(hash)
                .map(b -> String.format("%02x", b))
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                .toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
ssofyKnowledge Base
At our core, we believe that staying up-to-date with the latest trends and advancements in Authentication and related areas is essential. That's why we take great pride in keeping you informed with the latest insights, updates, and news in this rapidly evolving landscape.


Do you need support?
SSOfy is by Cubelet Ltd.
Copyright © 2024 Cubelet Ltd. All rights reserved.