Skip to content

Server API Authentication Code

ulkeroz edited this page Mar 27, 2015 · 2 revisions

Oluşturulan hash'i kontrol etmek için : http://www.freeformatter.com/hmac-generator.html

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

import org.apache.commons.codec.binary.Hex;

public class TokenBasedAuthenticationMain {

	private String algorithm = "HmacMD5";

	public void authenticate(String apiKey, Long id, Long time) {

		try {
			SecretKey sk = new SecretKeySpec(apiKey.getBytes(), 0, apiKey.length(), algorithm);
			Mac mac = Mac.getInstance(algorithm);
			mac.init(sk);
			String key = new StringBuffer().append(id).append(time).append(apiKey).toString();

			byte[] result = mac.doFinal(key.getBytes());

			String token = new String(Hex.encodeHex(result));
			System.out.println("Id: "+ id + " Time:" + time  + " ApiKey:" + apiKey +  " key:" + key);
			System.out.println("token is: " + token);
	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Clone this wiki locally