DataHandler angepasst
[staff/due1/sed-hs15-srs-purple.git] / src / main / java / ch / bfh / ti / srs / extern / Password.java
CommitLineData
ed6d035d 1package ch.bfh.ti.srs.extern;\r
7f912ebe
M
2\r
3import javax.crypto.SecretKey;\r
4import javax.crypto.SecretKeyFactory;\r
5import javax.crypto.spec.PBEKeySpec;\r
6import java.security.SecureRandom;\r
7import org.apache.commons.codec.binary.Base64;\r
8\r
9public class Password {\r
10 // The higher the number of iterations the more \r
11 // expensive computing the hash is for us and\r
12 // also for an attacker.\r
13 private static final int iterations = 20*1000;\r
14 private static final int saltLen = 32;\r
15 private static final int desiredKeyLen = 256;\r
16\r
17 /** Computes a salted PBKDF2 hash of given plaintext password\r
18 suitable for storing in a database. \r
19 Empty passwords are not supported. */\r
20 public static String getSaltedHash(String password) throws Exception {\r
21 byte[] salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLen);\r
22 // store the salt with the password\r
23 return Base64.encodeBase64String(salt) + "$" + hash(password, salt);\r
24 }\r
25\r
26 /** Checks whether given plaintext password corresponds \r
27 to a stored salted hash of the password. */\r
28 public static boolean check(String password, String stored) throws Exception{\r
29 String[] saltAndPass = stored.split("\\$");\r
30 if (saltAndPass.length != 2) {\r
31 throw new IllegalStateException(\r
32 "The stored password have the form 'salt$hash'");\r
33 }\r
34 String hashOfInput = hash(password, Base64.decodeBase64(saltAndPass[0]));\r
35 return hashOfInput.equals(saltAndPass[1]);\r
36 }\r
37\r
38 // using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt\r
39 // cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html\r
40 private static String hash(String password, byte[] salt) throws Exception {\r
41 if (password == null || password.length() == 0)\r
42 throw new IllegalArgumentException("Empty passwords are not supported.");\r
43 SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");\r
44 SecretKey key = f.generateSecret(new PBEKeySpec(\r
45 password.toCharArray(), salt, iterations, desiredKeyLen)\r
46 );\r
47 return Base64.encodeBase64String(key.getEncoded());\r
48 }\r
49}\r