Question

I've got this piece of js code which I need to convert to proper java code for usage in my Android app:

toHex(Crypto.util.bytesToBase64(Crypto.SHA1(password, { asBytes: true })));

I've found out that for the Crypto.util.bytesToBase64() method, I can use the java version: Base64.encode(), but I've got no clue how to call the js CryptoSHA1() and toHex() methods in java. Any ideas?

Was it helpful?

Solution

The code uses three functions:

  1. SHA-1 digest

    MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] digest = md.digest(text.getBytes("UTF-8"));

  2. Base 64

    String base64 = android.util.Base64.encodeToString(digest)

  3. Hex

Use a function like this: http://vinnysoft.blogspot.de/2010/11/code-snippet-to-convert-string-to-hex.html

In summary the last step is totally unnecessary and only blows up the data. The result of base64 is already a printable ASCII String.

Furthermore hashing a password using SHA-1 can be insecure depending what you do with the result. Usually password hashing should always incorporate salting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top