공공 키 기반 해석 jwt 영패 생성

10350 단어 code
4
  • 생성 jwt
  • import com.alibaba.fastjson.JSON;
    import org.junit.Test;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.security.jwt.Jwt;
    import org.springframework.security.jwt.JwtHelper;
    import org.springframework.security.jwt.crypto.sign.RsaSigner;
    import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
    
    import java.security.KeyPair;
    import java.security.interfaces.RSAPrivateKey;
    import java.util.HashMap;
    import java.util.Map;
    
    public class CreateJwtTest {
        @Test
        public void createJwt(){
            // 1.      jwt
            //         ,
            ClassPathResource classPathResource = new ClassPathResource("xk.jks");
            //     ,         。
            String keyPass = "xk";
            //       
            KeyStoreKeyFactory factory = new KeyStoreKeyFactory(classPathResource, keyPass.toCharArray());
            // 2.        
            //     ,    
            String alias = "xk";
            String password = "xk";
            KeyPair keyPair = factory.getKeyPair(alias, password.toCharArray());
            //       RSA  
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            //   jwt
            Map<String, String> map = new HashMap<>();
            map.put("name","zhangsan");
            map.put("age","18");
    
            Jwt jwt = JwtHelper.encode(JSON.toJSONString(map), new RsaSigner(rsaPrivateKey));
            String encoded = jwt.getEncoded();
            System.out.println(encoded);
        }
    }
    

    4
  • 해석 jwt
  • public class ParseJwtTest {
    
        @Test
        public void parseJwt(){
            String jwt = "jwt  ";
            String publicKey = "  ";
            Jwt token = JwtHelper.decodeAndVerify(jwt, new RsaVerifier(publicKey));
            String claims = token.getClaims();
            System.out.println(claims);
        }
    }
    

    좋은 웹페이지 즐겨찾기