I have a Java method that I need to implement in PHP. It is to create an authentication string to gain access to an API. It consists of a code given by the company as well as an API key, also given by the company, and, according to the Java example below, it also includes a GMT timestamp in minutes since epoch.
According to the documentation it says "The timestamp calculated as the number of minutes passed since epoch. A GMT time zone must be used for calculating the timestamp. If the system time of a requesting server is off by more than one minute from actual current time , the call will be rejected by the server with a 400 Bad Request code".
I have to provide as parameters the code as well as the SHA-256 encrypted token that I create.
Here is the Java:
String createToken() {
String token = "";
MessageDigest lclMD = null;
try {
lclMD = MessageDigest.getInstance("SHA-256"); }
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
lclMD.update((EnvConstants.code + EnvConstants.api_key + Long.toString(getEpochMinutes())).getBytes());
byte[] lclResult = lclMD.digest();
sig = new String(Hex.encodeHex(lclResult));
return token;
}
long getEpochMinutes () {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long now = System.currentTimeMillis();
cal.setTimeInMillis(now);
return (cal.getTimeInMillis() / 60000L);
}
This is what I have tried in PHP:
$time = (string)time()/60; // to get the minutes since epoch, I have also tried it not casting it to a string
$code = 'thisisthecode';
$api_key = 'XXXXXXX';
$hash = hash('sha256', $code . $api_key . $time);
$curl = curl_init();
$url = "http://api.url/user/XXXX?code=thisisthecode&token=$hash";
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
return $result;
When I run this code I always get a 400 Bad Request error.
To be clear, I don't know Java and now I'm guessing if I know PHP well enough because I can't get this to work.
Can anyone help me out with this? I'm banging my head against the concrete.
Thank you for any and all help.
$ key = openssl_digest($ stringSHA,'sha512',true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.