Commit 749f7195 by amir

Add missing files

parent d9c5f3e7
package microservice.common;
import io.jsonwebtoken.*;
import microservice.types.UserProfile;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
/**
* Created by amir on 03/08/16.
*/
public class EncryptionUtils {
public final static String JWT_SALT = System.getProperty("jwt.salt","12345678901234567890123456789012");
private static int workload = 5;
public static String getSHA256Hash(String data){
String encrypted = null;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes());
byte byteData[] = md.digest();
encrypted = DatatypeConverter.printHexBinary(byteData).toLowerCase();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return encrypted;
}
public static String getBcryptHash(String data, String salt){
if (salt == null)
salt = BCrypt.gensalt(workload);
return BCrypt.hashpw(data, salt);
}
public static boolean checkPassword(String password_plaintext, String stored_hash) {
boolean password_verified = false;
if(null == stored_hash || !stored_hash.startsWith("$2a$"))
throw new java.lang.IllegalArgumentException("Invalid hash provided for comparison");
password_verified = BCrypt.checkpw(password_plaintext, stored_hash);
return(password_verified);
}
public static String createJWT(UserProfile userProfile, long ttlMillis) {
// validate user Profile
if (userProfile.valid()) {
//The JWT signature algorithm we will be using to sign the token
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//We will sign our JWT with our ApiKey secret
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(JWT_SALT);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
userProfile.setIssuedAt(now);
//Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(userProfile.getId())
.setIssuedAt(now)
.setSubject(userProfile.getSubject())
.setIssuer(userProfile.getIssuer())
.claim(UserProfile.SERVICE_AUTHORIZATION,userProfile.getServiceAuthorizations())
.claim(UserProfile.USER_ATTRIBUTES,userProfile.getAttributes())
.signWith(signatureAlgorithm, signingKey);
//if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
//Builds the JWT and serializes it to a compact, URL-safe string
return builder.compact();
}
else
return null;
}
public static UserProfile parseJWT(String jwt) throws ExpiredJwtException {
//This line will throw an exception if it is not a signed JWS (as expected)
try{
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(JWT_SALT))
.parseClaimsJws(jwt).getBody();
return new UserProfile(claims);
}catch (MalformedJwtException exp){
System.out.println(exp.toString());
}catch (SignatureException exp) {
System.out.println(exp.toString());
} catch (UnsupportedJwtException exp){
System.out.println(exp.toString());
}
return null;
}
}
package microservice.types;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.impl.DefaultClaims;
import microservice.defs.Enums;
import java.util.HashMap;
import java.util.Map;
/**
* Created by amir on 02/08/16.
*/
public class UserProfile extends DefaultClaims {
public static final String ALL_SERVICES = "*";
public static final String SERVICE_AUTHORIZATION = "serviceAuth";
public static final String USER_ATTRIBUTES = "userAttrib";
public static final String FULL_AUTHORIZATION = "YYYY";
private Map<String,String> serviceAuthorizations = new HashMap<>();
private Map<String,String> attributes = new HashMap<>();
public UserProfile() {
}
public UserProfile(Claims claims) {
super(claims);
serviceAuthorizations.putAll(claims.get(SERVICE_AUTHORIZATION,serviceAuthorizations.getClass()));
attributes.putAll(claims.get(USER_ATTRIBUTES,attributes.getClass()));
}
public UserProfile addServiceAuthorization(String serviceName,
boolean create,
boolean read,
boolean update,
boolean delete){
char[] serviceAuth = new char[4];
serviceAuth[0] = create ? 'Y' : 'N';
serviceAuth[1] = read ? 'Y' : 'N';
serviceAuth[2] = update ? 'Y' : 'N';
serviceAuth[3] = delete ? 'Y' : 'N';
serviceAuthorizations.put(serviceName,new String(serviceAuth));
return this;
}
public UserProfile addServiceFullAuthorization(String serviceName){
serviceAuthorizations.put(serviceName,FULL_AUTHORIZATION);
return this;
}
public UserProfile setAllServicesFullAuthorization(){
serviceAuthorizations.put(ALL_SERVICES,FULL_AUTHORIZATION);
return this;
}
public void setServiceAuthorizations(Map<String, String> serviceAuthorizations) {
this.serviceAuthorizations = serviceAuthorizations;
}
public Map<String, String> getServiceAuthorizations() {
return serviceAuthorizations;
}
public boolean isServiceAuthorized(String serviceName, Enums.EnumCrudMethod enumCrudMethod){
boolean authorized = false;
String serviceAuth = serviceAuthorizations.get(serviceName);
if (serviceAuth == null) // check for all services authorizations
serviceAuth = serviceAuthorizations.get(ALL_SERVICES);
if(serviceAuth != null)
authorized = serviceAuth.getBytes()[enumCrudMethod.ordinal()] == 'Y';
return authorized;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public void setAttribute(String key, String value){
attributes.put(key,value);
}
public String getAttribute(String key){
return attributes.get(key);
}
public boolean valid(){
if (this.getId() != null &&
this.getSubject() != null &&
this.getIssuer() != null &&
!serviceAuthorizations.isEmpty() )
return true;
return false;
}
}
package microservice;
import io.jsonwebtoken.ExpiredJwtException;
import microservice.common.EncryptionUtils;
import microservice.types.UserProfile;
import org.junit.Test;
import static microservice.common.EncryptionUtils.checkPassword;
/**
* Created by amir on 03/08/16.
*/
public class TestEncryption {
public static final String ID = "97297705810";
public static final String IDENTITY = "identity";
public static final String AMIR = "amir";
public static final int ITERATIONS = 100000;
@Test
public void testEncryption()
{
String userpass = "97297705810.password";
String dbhash = "$2a$05$O03p6krljLmeqIGtuumS9e.9FmdBlsUlP9/XEVF.VYOjaokDlsKUG";
String salt = "$2a$05$IxABv8ni847HEvT.4THfwe";
String enc = EncryptionUtils.getBcryptHash(userpass,null);
enc = EncryptionUtils.getBcryptHash(userpass,salt);
boolean compare = checkPassword(enc,dbhash);
enc = EncryptionUtils.getSHA256Hash(userpass);
}
@Test
public void testBcrypt()
{
String test_passwd = "abcdefghijklmnopqrstuvwxyz";
String test_hash = "$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC";
System.out.println("Testing BCrypt Password hashing and verification");
System.out.println("Test password: " + test_passwd);
System.out.println("Test stored hash: " + test_hash);
System.out.println("Hashing test password...");
System.out.println();
String computed_hash = EncryptionUtils.getBcryptHash(test_passwd,null);
System.out.println("Test computed hash: " + computed_hash);
System.out.println();
System.out.println("Verifying that hash and stored hash both match for the test password...");
System.out.println();
String compare_test = checkPassword(test_passwd, test_hash)
? "Passwords Match" : "Passwords do not match";
String compare_computed = checkPassword(test_passwd, computed_hash)
? "Passwords Match" : "Passwords do not match";
System.out.println("Verify against stored hash: " + compare_test);
System.out.println("Verify against computed hash: " + compare_computed);
}
@Test
public void testJwtPerformance()
{
UserProfile up = new UserProfile();
up.setId(ID).setIssuer(IDENTITY).setSubject(AMIR);
up.addServiceAuthorization("cse",true,true,false,false);
up.addServiceFullAuthorization("transport");
System.out.println("Iterations: " + String.valueOf(ITERATIONS));
long startMilli = System.currentTimeMillis();
System.out.println("Start: " + startMilli);
for(int i = 0; i < ITERATIONS; i++) {
String jwt = EncryptionUtils.createJWT(up, 10000);
try {
UserProfile userProfile = EncryptionUtils.parseJWT(jwt);
} catch (ExpiredJwtException exception) {
System.out.println("expired token");
}
}
System.out.println("Test time: " + String.valueOf(System.currentTimeMillis() - startMilli));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment