0

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?

Xander
  • 5,487
  • 14
  • 49
  • 77
  • Do you *really* need the `toHex` part? By the time you've converted it to base64, it's ASCII text anyway... as for the `SHA1` part, a search for SHA1 and Java should get you lots of hits... – Jon Skeet Apr 19 '14 at 08:45
  • @JonSkeet Well this is what the js code looks like. This output is posted to a server, so I bet the `toHex` is needed. Not 100% sure though – Xander Apr 19 '14 at 08:48
  • http://stackoverflow.com/questions/4400774/java-calculate-a-sha1-of-a-string – Schabowy Apr 19 '14 at 08:51

1 Answers1

2

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.

Robert
  • 39,162
  • 17
  • 99
  • 152