Reputation: 115
I am trying to implement Java's StandardStringDigester digest function in PHP to digest a string with the SHA-1 algorithm. I do not have experience with encryption, so I have tried a few things without understanding them. The Working Java example is following:
import java.net.URLEncoder;
import org.jasypt.digest.StandardStringDigester;
import java.io.UnsupportedEncodingException;
public class Main
{
public static void main (String[]args)
{
String x = "XUXoV2VYc7zYJ8UN";
int n = 854;
StandardStringDigester clientsd = new StandardStringDigester ();
clientsd.setIterations (n - 1);
clientsd.setAlgorithm ("SHA-1");
clientsd.setSaltSizeBytes (0); //no salt
String clientDigest = clientsd.digest (x);
String URLclientDigest = "a";
try {
URLclientDigest = URLEncoder.encode (clientDigest, "UTF-8");
} catch(UnsupportedEncodingException ex){
System.out.println("Encoding not supported");
ex.printStackTrace();
}
System.out.println (URLclientDigest);
}
}
In PHP I tried few things:
$n = 854;
$x = 'XUXoV2VYc7zYJ8UN';
return hash_pbkdf2('sha1', $x, null, $n);
I also tried the above code with $n -1
.
In above examples x
is the message and n
is the iterations.
I am not really sure what I am doing here. Perhaps there is a PHP library someone can point me to or any direcction will be appreciated.
Upvotes: 1
Views: 103
Reputation: 49276
According to the documentation of StandardStringDigester
(which is part of the Jasypt library), the hash is generated as follows:
The steps taken for creating digests are:
- The String message is converted to a byte array
- A salt of the specified size is generated (see SaltGenerator).
- The salt bytes are added to the message.
- The hash function is applied to the salt and message altogether, and then to the results of the function itself, as many times as specified (iterations).
- If specified by the salt generator (see SaltGenerator.includePlainSaltInEncryptionResults()), the undigested salt and the final result of the hash function are concatenated and returned as a result.
- The result of the concatenation is encoded in BASE64 or HEXADECIMAL and returned as an ASCII String.
Since no salt is used in your case, a possible PHP implementation is:
$n = 854;
$x = 'XUXoV2VYc7zYJ8UN';
$hash = $x;
for ($counter = 0; $counter < $n - 1; $counter++){
$hash = hash('sha1', $hash, true);
}
print(base64_encode($hash)); // QGFgek+pfZ6nMk8Jn3stOe5KeEY=
with the result QGFgek+pfZ6nMk8Jn3stOe5KeEY=
analogous to the Java code (before the URL encoding).
Note: If a salt is used in the Java code (e.g. with ByteArrayFixedSaltGenerator
), the salt in the PHP code must be concatenated with the message before the loop: $hash = $salt . $x;
(instead of $hash = $x;
).
Upvotes: 3