All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.dream.utils.SecurityHelper Maven / Gradle / Ivy

The newest version!
package com.dream.utils;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

@Component
public class SecurityHelper {

	private static String KEY;
	
	// Overcoming Spring's unavailability to set the value to static field
	@Value("${the_key}")
	public void setKey(String key) {
		SecurityHelper.KEY = key;
	}
	
    public static boolean isLogged() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof User) {
            return authentication.isAuthenticated();
        }
        return false;
    }
    
    public static String hash(String text) {
        Mac sha512Hmac;
        String result = "";
        
        try {
            final byte[] byteKey = KEY.getBytes(StandardCharsets.UTF_8);
            sha512Hmac = Mac.getInstance("HmacSHA512");
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, "HmacSHA512");
            sha512Hmac.init(keySpec);
            byte[] macData = sha512Hmac.doFinal(text.getBytes(StandardCharsets.UTF_8));

            // Can either base64 encode or put it right into hex
            result = Base64.getEncoder().encodeToString(macData);
            //result = bytesToHex(macData);
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy