andypiper
6/19/2017 - 3:09 PM

Java snippet to generate Twitter Webhooks CRC response

Java snippet to generate Twitter Webhooks CRC response

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class CRC_Example {
  public static void main(String[] args) {
    try {
     String consumer_secret = "secret";
     String crc_token = "Message";

     Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
     SecretKeySpec secret_key = new SecretKeySpec(consumer_secret.getBytes("UTF-8"), "HmacSHA256");
     sha256_HMAC.init(secret_key);

     String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(crc_token.getBytes("UTF-8")));

     System.out.println("sha256=" + hash);
    }
    catch (Exception e){
     System.out.println("Error");
    }
   }
}

Requires Apache Commons Codec

Usage:

$ javac ./CRC_Example.java -cp ./commons-codec-1.10/commons-codec-1.10.jar
$ java -cp .:./commons-codec-1.10/commons-codec-1.10.jar CRC_Example