View Javadoc
1   package org.oxerr.okcoin.rest;
2   
3   import static java.lang.String.format;
4   import static java.nio.charset.StandardCharsets.UTF_8;
5   
6   import java.security.MessageDigest;
7   import java.security.NoSuchAlgorithmException;
8   import java.util.Map;
9   import java.util.TreeMap;
10  
11  import javax.ws.rs.FormParam;
12  
13  import org.knowm.xchange.utils.DigestUtils;
14  import org.slf4j.Logger;
15  import org.slf4j.LoggerFactory;
16  
17  import si.mazi.rescu.Params;
18  import si.mazi.rescu.ParamsDigest;
19  import si.mazi.rescu.RestInvocation;
20  
21  /**
22   * {@link ParamsDigest} implementation.
23   */
24  public class OKCoinDigest implements ParamsDigest {
25  
26  	private final Logger log = LoggerFactory.getLogger(OKCoinDigest.class);
27  
28  	private final String secretKey;
29  	private final MessageDigest md;
30  
31  	public OKCoinDigest(String secretKey) {
32  		this.secretKey = secretKey;
33  		try {
34  			this.md = MessageDigest.getInstance("MD5");
35  		} catch (NoSuchAlgorithmException e) {
36  			throw new RuntimeException(e);
37  		}
38  	}
39  
40  	/**
41  	 * {@inheritDoc}
42  	 */
43  	@Override
44  	public String digestParams(RestInvocation restInvocation) {
45  		return digestParams(restInvocation.getParamsMap().get(FormParam.class).asHttpHeaders());
46  	}
47  
48  	public String digestParams(Map<String, String> parameters) {
49  		Params params = Params.of();
50  
51  		new TreeMap<>(parameters)
52  				.entrySet()
53  				.stream()
54  				.filter(e -> !e.getKey().equals("sign"))
55  				.forEach(e -> params.add(e.getKey(), e.getValue()));
56  
57  		String payload = format("%s&secret_key=%s", params.toString(), secretKey);
58  		log.trace("payload: {}", payload);
59  
60  		return DigestUtils.bytesToHex(md.digest(payload.getBytes(UTF_8)));
61  	}
62  
63  }