Last active
October 10, 2015 18:57
-
-
Save vanduc1102/33a79f7da0074c490ca6 to your computer and use it in GitHub Desktop.
Working with token and password in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<dependencies> | |
<dependency> | |
<groupId>junit</groupId> | |
<artifactId>junit</artifactId> | |
<version>3.8.1</version> | |
<scope>test</scope> | |
</dependency> | |
<dependency> | |
<groupId>io.jsonwebtoken</groupId> | |
<artifactId>jjwt</artifactId> | |
<version>0.5.1</version> | |
</dependency> | |
<dependency> | |
<groupId>commons-codec</groupId> | |
<artifactId>commons-codec</artifactId> | |
<version>1.9</version> | |
</dependency> | |
</dependencies> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.token; | |
import javax.crypto.SecretKey; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.PBEKeySpec; | |
import java.security.SecureRandom; | |
import org.apache.commons.codec.binary.Base64; | |
public class Password { | |
// The higher the number of iterations the more | |
// expensive computing the hash is for us and | |
// also for an attacker. | |
private static final int iterations = 20*1000; | |
private static final int saltLen = 32; | |
private static final int desiredKeyLen = 256; | |
/** Computes a salted PBKDF2 hash of given plaintext password | |
suitable for storing in a database. | |
Empty passwords are not supported. */ | |
public static String getSaltedHash(String password) throws Exception { | |
byte[] salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLen); | |
// store the salt with the password | |
return Base64.encodeBase64String(salt) + "$" + hash(password, salt); | |
} | |
/** Checks whether given plaintext password corresponds | |
to a stored salted hash of the password. */ | |
public static boolean check(String password, String stored) throws Exception{ | |
String[] saltAndPass = stored.split("\\$"); | |
if (saltAndPass.length != 2) { | |
throw new IllegalStateException( | |
"The stored password have the form 'salt$hash'"); | |
} | |
String hashOfInput = hash(password, Base64.decodeBase64(saltAndPass[0])); | |
return hashOfInput.equals(saltAndPass[1]); | |
} | |
// using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt | |
// cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html | |
private static String hash(String password, byte[] salt) throws Exception { | |
if (password == null || password.length() == 0) | |
throw new IllegalArgumentException("Empty passwords are not supported."); | |
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); | |
SecretKey key = f.generateSecret(new PBEKeySpec( | |
password.toCharArray(), salt, iterations, desiredKeyLen) | |
); | |
return Base64.encodeBase64String(key.getEncoded()); | |
} | |
public static void main (String args[]){ | |
String password ="123123123"; | |
try { | |
String stored = getSaltedHash(password); | |
System.out.println("stored password :"+stored); | |
System.out.println("check valid : "+ check(password, stored)); | |
} catch (Exception e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.token; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.spec.InvalidKeySpecException; | |
import java.security.spec.KeySpec; | |
import java.util.Date; | |
import java.util.Random; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.PBEKeySpec; | |
import org.apache.commons.codec.binary.Base64; | |
import io.jsonwebtoken.Claims; | |
import io.jsonwebtoken.Jwts; | |
import io.jsonwebtoken.MalformedJwtException; | |
import io.jsonwebtoken.SignatureAlgorithm; | |
import io.jsonwebtoken.SignatureException; | |
/** | |
* Hello world! | |
* | |
*/ | |
public class App { | |
private static String ISSUER = "nguyenvanduc.com"; | |
private static String CAT_KEY = "glN47XH49J4wYWyIu7rdlr0o652nzG1C"; | |
public static void main(String[] args) { | |
System.out.println("Hello World!"); | |
// the key would be read from your application configuration instead. | |
// Key key = MacProvider.generateKey(); | |
// System.out.println("key "+ key); | |
String subject = "Hello World"; | |
String s = Jwts.builder().setSubject(subject) | |
.setIssuedAt(new Date()) | |
.setIssuer(ISSUER) | |
.signWith(SignatureAlgorithm.HS512, CAT_KEY).compact(); | |
System.out.println("s :" + s); | |
TestHash(subject); | |
} | |
public static char getRandomChar(){ | |
Random r = new Random(); | |
char c = (char)(r.nextInt(26) + 'a'); | |
return c; | |
} | |
public static void testDecryption (String s){ | |
String newEncrypted=""; | |
for(int i = 0 ; i < 100 ; i ++){ | |
char c1 = getRandomChar(); | |
char c2 = getRandomChar(); | |
newEncrypted = s.replace(c1,c2); | |
try { | |
Claims claims = Jwts.parser().setSigningKey(CAT_KEY).parseClaimsJws(newEncrypted).getBody(); | |
System.out.println("Parse successfull : "+ claims.getSubject()); | |
System.out.println("char1 : "+ c1 + " ; char2 : "+ c2); | |
//OK, we can trust this JWT | |
} catch (SignatureException e) { | |
System.out.println("Parse failure"); | |
//don't trust the JWT | |
}catch (MalformedJwtException e){ | |
System.out.println("Parse failure : wrong format"); | |
} | |
} | |
} | |
public static void TestHash(String text){ | |
byte[] salt = new byte[16]; | |
Random random = new Random(); | |
random.nextBytes(salt); | |
KeySpec spec = new PBEKeySpec(text.toCharArray(), salt, 65536, 128); | |
SecretKeyFactory f; | |
try { | |
f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); | |
byte[] hash = f.generateSecret(spec).getEncoded(); | |
System.out.printf("salt: %s%n", salt); | |
System.out.printf("hash: %s%n", hash); | |
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment