Skip to content

Instantly share code, notes, and snippets.

@kimathie
Last active April 17, 2020 22:34
Show Gist options
  • Save kimathie/622862e807686d4d1113e1b5df903841 to your computer and use it in GitHub Desktop.
Save kimathie/622862e807686d4d1113e1b5df903841 to your computer and use it in GitHub Desktop.
step-by-step-auth-token
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
/**
*
* @author kimathie
*/
public class SendbeeAuthToken {
public static void main(String[] args) {
/**
* Assigned secret key
*/
String secret_key = "zodux3ITAPW4cGsvn6rGbLEAgRNLphPJ7OF121nl";
try {
/**
* Step 1: get current timestamp (in seconds)
* Use the line below to generate current timestamp in seconds as a String
*
* Long.toString(Instant.now().getEpochSecond());
*/
String timestamp = "1586286575";
/**
* Step 2: encrypt the timestamp with your API secret key using HMAC
* sha256 encrypt algorithm
*/
String lowerHexit_UTF_8_Hash = SendbeeAuthToken.hmac256LowerHexit(secret_key, timestamp, StandardCharsets.UTF_8.name());
System.out.println("Lower Hexit UTF_8 Hash: " + lowerHexit_UTF_8_Hash);
/**
* Step 3: concatenate timestamp and encrypted timestamp separated
* by a . (dot)
*/
String lowerHexit_UTF_8_Hash_Concatenate = timestamp + "." + lowerHexit_UTF_8_Hash;
System.out.println("Lower Hexit UTF_8 Hash Concatenate: " + lowerHexit_UTF_8_Hash_Concatenate);
/**
* Step 4: translate concatenated string into base64
*/
String lowerHexit_UTF_8_Hash_Concatenate_Token = DatatypeConverter.printBase64Binary(lowerHexit_UTF_8_Hash_Concatenate.getBytes(StandardCharsets.UTF_8));
System.out.println("Lower Hexit UTF_8_Hash_Concatenate_Token: " + lowerHexit_UTF_8_Hash_Concatenate_Token);
} catch (Exception ex) {
Logger.getLogger(SendbeeAuthToken.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
* @param key A secret cryptographic key
* @param data The information to be encrypted
* @param charsetName the encoding to be used
* @return A String representation of the hash
* @throws Exception
*/
public static String hmac256LowerHexit(String key, String data, String charsetName) throws Exception {
return toLowerHexit(hmac256Raw(key, data, charsetName));
}
/**
* Encrypts the data into raw bytes using the encoding of choice
*/
public static byte[] hmac256Raw(String key, String data, String charsetName) throws Exception {
Mac hasher = Mac.getInstance("HmacSHA256");
hasher.init(new SecretKeySpec(key.getBytes(charsetName), "HmacSHA256"));
return hasher.doFinal(data.getBytes(charsetName));
}
/**
* Returns the lower representation of the hexadecimal bits
*/
private static String toLowerHexit(byte[] value) {
String hexed = String.format("%040x", new BigInteger(1, value));
return hexed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment