Skip to content

Instantly share code, notes, and snippets.

@JCBarry
Created April 29, 2015 15:05
Show Gist options
  • Save JCBarry/c52f6522054625b3fbbd to your computer and use it in GitHub Desktop.
Save JCBarry/c52f6522054625b3fbbd to your computer and use it in GitHub Desktop.
Apex Legit CC Example
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.spec.SecretKeySpec;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.lang.JoseException;
public class Main {
public static void main(String[] args) throws JoseException, NoSuchAlgorithmException, InvalidKeyException {
DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZ");
JsonWebSignature jws = new JsonWebSignature();
// Assign variables from provided credentials.json file
String username = "";
String entity = "";
String secret = "";
String payload = ("{'username': '" + username + "', 'datetime': '" + fmt.print(dt) + "', 'entity': '" + entity + "'}");
// JSON in Java likes double-quotes instead of single
payload = payload.replaceAll("'", "\"");
// Create the secret key spec from the shared secret
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HS512");
// Set all the variables for the JWS
jws.setKey(secretKey);
jws.setPayload(payload);
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
// Output the JWS string
System.out.println(jws.getCompactSerialization());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment