84 lines
2.5 KiB
Java
84 lines
2.5 KiB
Java
package eu.eudat.security;
|
|
|
|
import java.security.MessageDigest;
|
|
import java.security.NoSuchAlgorithmException;
|
|
import java.security.SecureRandom;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
import com.google.common.cache.Cache;
|
|
import com.google.common.cache.CacheBuilder;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
@Service
|
|
public class TokenSessionManager {
|
|
|
|
private final static long TOTAL_SESSION_MINUTES = 120L;
|
|
private final static long IDLE_MINUTES_EXPIRE = 20L;
|
|
|
|
private static Cache <String, String> cache; //that's thread-safe according to the documentation
|
|
|
|
private static TokenSessionManager instance = null; //should be one-per-classloader
|
|
|
|
|
|
public static synchronized TokenSessionManager getInstance() {
|
|
if (instance == null){
|
|
instance = new TokenSessionManager();
|
|
initialize();
|
|
}
|
|
return instance;
|
|
}
|
|
|
|
private static void initialize() {
|
|
cache = CacheBuilder.newBuilder()
|
|
.expireAfterWrite(TOTAL_SESSION_MINUTES, TimeUnit.MINUTES)
|
|
.expireAfterAccess(IDLE_MINUTES_EXPIRE, TimeUnit.MINUTES)
|
|
.maximumSize(Long.MAX_VALUE)
|
|
.build();
|
|
}
|
|
|
|
public String getUser(String token) {
|
|
return cache.getIfPresent(token);
|
|
}
|
|
|
|
public void set(String token, String user) {
|
|
cache.put(token, user);
|
|
}
|
|
|
|
public String generateRandomAlphanumeric(int length) {
|
|
SecureRandom random = new SecureRandom();
|
|
byte bytes[] = new byte[length];
|
|
random.nextBytes(bytes);
|
|
return encode(bytes);
|
|
}
|
|
|
|
|
|
private String encode(byte[] binaryData) {
|
|
int n = binaryData.length;
|
|
char[] HEXADECIMAL = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
|
|
char[] buffer = new char[n * 2];
|
|
for (int i = 0; i < n; i++) {
|
|
int low = (binaryData[i] & 0x0f);
|
|
int high = ((binaryData[i] & 0xf0) >> 4);
|
|
buffer[i * 2] = HEXADECIMAL[high];
|
|
buffer[(i * 2) + 1] = HEXADECIMAL[low];
|
|
}
|
|
return new String(buffer);
|
|
}
|
|
|
|
|
|
public String hashPassword (String password) throws NoSuchAlgorithmException {
|
|
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
|
md.update(password.getBytes());
|
|
byte byteData[] = md.digest();
|
|
StringBuffer sb = new StringBuffer();
|
|
for (int i = 0; i < byteData.length; i++)
|
|
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
|
|
return sb.toString();
|
|
}
|
|
|
|
// public static void main(String [] args) throws NoSuchAlgorithmException {
|
|
// System.out.println(TokenSessionManager.getInstance().hashPassword("apa$$2gu3$$"));
|
|
// }
|
|
|
|
}
|