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

foundation.cmo.api.mls.graphql.security.services.JwtService Maven / Gradle / Ivy

There is a newer version: 1.0.21
Show newest version
package foundation.cmo.api.mls.graphql.security.services;

import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import foundation.cmo.api.mls.graphql.security.dto.MUserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
//@EnableConfigurationProperties(MGraphQLProperty.class)
public class JwtService {
	@Value("${foundation.cmo.service.security.signing:m4rc310}")
	private String jwtSigningKey;

	@Value("${foundation.cmo.service.security.expiration:864000000}")
	private Long expiration;

	
	public String generateToken(MUserDetails userDetails) {
        Map claims = new HashMap<>();
        return createToken(claims, userDetails);
    }

    public Boolean isTokenValid(String token, UserDetails userDetails) {
        final String username = extractUsername(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
    
    //=====================================================//
    public static void main(String[] args) throws Exception {
    	//try {
    		log.info("Erros");
//    		char[] ckey = "cmo.foundation".toCharArray();
//    		byte[] salt = "m4rc310".getBytes();
//    		
 //   		String scrypto = "U2FsdGVkX1+sUF1Vzm5lmSDlGoTejPexOU31Fb4w5hY=";
//    		
//    		int keySize = 128;
//    		int nIterations = 10000;
//    		
////    		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBDKF2WithHmacSHA256");
////    		SecretKeyS
//            KeySpec spec = new PBEKeySpec(ckey, salt, nIterations, keySize);
//            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
//
//            byte[] keyBytes = factory.generateSecret(spec).getEncoded();
//            
//            String keyBase64 = Base64.getEncoder().encodeToString(keyBytes);
//            
//            keyBase64 = "TM78vctyH3p2Ed4um85hpQ==";
//            
//            log.info(keyBase64);
    		
//    		String chave = Base64.getEncoder().encodeToString(new JwtService().getKeyByte());
//    		
//    		log.info(chave);
//    		
//    		SecretKeySpec chaveAES = new SecretKeySpec(chave.getBytes(), "AES");
//            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//            cipher.init(Cipher.ENCRYPT_MODE, chaveAES);
//            
//            byte[] crypto = cipher.doFinal("mls".getBytes());
//            
//            String sdecrypt = Base64.getEncoder().encodeToString(crypto);
//    		
//    		log.info(sdecrypt);
//    		
////
//    		Key key = new SecretKeySpec(chave.getBytes(), "AES");
//            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//            
//            
//            cipher.init(Cipher.DECRYPT_MODE, key);
//            byte[] textoBytes = Base64.getDecoder().decode(sdecrypt);
//            byte[] textoDescriptografado = cipher.doFinal(textoBytes);
            
            
            
//            
//            byte[] textBytes = Base64.getDecoder().decode(scrypto);
//            scrypto = new String(cipher.doFinal(textBytes));
            
//            log.info("{}", new String(textoDescriptografado));
    		
            //log.info();
    		
    		
//    	} catch (Exception e) {
//    		e.printStackTrace();
//    	}
    	 String palavra = "mls";
         String chave = "3oUHQ6UixnfMHTi48AWS7A==";

         // Converter a chave de base64 para bytes
         byte[] chaveBytes = Base64.getDecoder().decode(chave);

         // Criptografar a palavra usando AES e a chave
         byte[] textoCriptografado = criptografar(palavra, chaveBytes);

         // Converter o texto criptografado para base64
         String textoCriptografadoBase64 = Base64.getEncoder().encodeToString(textoCriptografado);
         System.out.println("Texto criptografado no Java: " + textoCriptografadoBase64);
         
         
         textoCriptografado = Base64.getDecoder().decode("NdBCbd9nQnI0c7VPaUDlkzV/L0G1yjZf8tbZsDlFZxnRuOI2jPfe5EB1W+iRCL/8Um3BwSLMQVHVOxVRKfe+uunVC/W/ZKmKYfxS8p8iWs4=");
         
         //textoCriptografado = "viyhaH1MHwaPYDm8BEzCbg==".getBytes();
         
         String textoDescriptografado = descriptografar(textoCriptografado, chaveBytes);
         System.out.println("Texto descriptografado no Java: " + textoDescriptografado);
   
         
     }

     public static byte[] criptografar(String texto, byte[] chave) throws Exception {
         SecretKeySpec chaveAES = new SecretKeySpec(chave, "AES");
         Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
         cipher.init(Cipher.ENCRYPT_MODE, chaveAES);
         return cipher.doFinal(texto.getBytes());
     }
     
     public static String descriptografar(byte[] textoCriptografado, byte[] chave) throws Exception {
         SecretKeySpec chaveAES = new SecretKeySpec(chave, "AES");
         Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
         cipher.init(Cipher.DECRYPT_MODE, chaveAES);
         byte[] textoDescriptografado = cipher.doFinal(textoCriptografado);
         return new String(textoDescriptografado);
     }
    
    public byte[] getKeyByte() throws Exception {
    	String skey = "cmo.foundation";
    	String ssalt = "m4rc310";
    	int length = 128;
    	int interations = 10000;
    	PBEKeySpec spec = new PBEKeySpec(skey.toCharArray(), ssalt.getBytes(), interations, length);
    	SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    	return factory.generateSecret(spec).getEncoded();
    }
    
    
    public Key getKeyFromSingleKey(String cipher, int keysize, char[] key) throws Exception {
    	
    	byte[] salt = new byte[100];
        SecureRandom random = new SecureRandom();
        random.nextBytes(salt);
        
        PBEKeySpec pbeKeySpec = new PBEKeySpec(key, salt, 1000, keysize);
        SecretKey pbeKey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(pbeKeySpec);
        return new SecretKeySpec(pbeKey.getEncoded(), cipher);
    }
    
    
   //=====================================================//
    
    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }
	
    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public  T extractClaim(String token, Function claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }
    
    private Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(jwtSigningKey).parseClaimsJws(token).getBody();
    }

    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

	private String createToken(Map claims, MUserDetails userDetails) {

		Date now = new Date();
		Date dex = new Date(now.getTime() + expiration);
		
		return Jwts.builder().setClaims(claims).setSubject(userDetails.getUsername())
				.claim("authorities", userDetails.getAuthorities()).setIssuedAt(now).setExpiration(dex)
				.signWith(SignatureAlgorithm.HS256, jwtSigningKey).compact();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy