- jwt store/restore key

This commit is contained in:
2024-02-25 16:44:02 +09:00
parent 13f2867f99
commit 3a8509088f
2 changed files with 40 additions and 0 deletions

View File

@@ -10,6 +10,7 @@ import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyPair; import java.security.KeyPair;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
@@ -28,6 +29,18 @@ public class JwtsSample {
} }
public static byte[] getEncodedKey(SecretKey key) {
return key.getEncoded();
}
public static String getAlgorithmName(SecretKey key) {
return key.getAlgorithm();
}
public static SecretKey getSecretKey(byte[] encodedKey, String alg) {
return new SecretKeySpec(encodedKey, alg);
}
public static KeyPair generateKeyPair() { public static KeyPair generateKeyPair() {
return Jwts.SIG.RS512.keyPair().build(); return Jwts.SIG.RS512.keyPair().build();
@@ -76,6 +89,7 @@ public class JwtsSample {
throw e; throw e;
} }
} }
public static String decodeToken(final String token) throws JwtException { public static String decodeToken(final String token) throws JwtException {
String[] chunks = token.split("\\."); String[] chunks = token.split("\\.");
Base64.Decoder decoder = Base64.getUrlDecoder(); Base64.Decoder decoder = Base64.getUrlDecoder();
@@ -87,6 +101,7 @@ public class JwtsSample {
} }
public static String decodeToken2(final String token) throws JwtException { public static String decodeToken2(final String token) throws JwtException {
String s = Jwts.parser().unsecured().build().parseSignedClaims(token) String s = Jwts.parser().unsecured().build().parseSignedClaims(token)
.getPayload().getSubject(); .getPayload().getSubject();

View File

@@ -26,6 +26,31 @@ import java.util.Random;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
class SampleTest { class SampleTest {
@Test
void keyTest(){
SecretKey secretKey = JwtsSample.generateSecretKey();
byte[] rawKey = secretKey.getEncoded();
String alg = secretKey.getAlgorithm();
SecretKey secKey = JwtsSample.getSecretKey(rawKey, alg);
String token = Jwts.builder()
.header().type("JWT")
.and()
.issuer("Elex")
.expiration(Date.from(Instant.now().plus(3, ChronoUnit.HOURS)))
.claim("userId", 3)
.subject("hello")
.signWith(secretKey)
.compact();
String subject = Jwts.parser()
.verifyWith(secKey)
.requireIssuer("Elex") // 토큰의 Issuer 일치 여부 확인
.build().parseSignedClaims(token).getPayload().getSubject();
System.out.println(subject);
}
@Test @Test
void test2(){ void test2(){
final SecretKey signingKey = Jwts.SIG.HS384.key().build(); final SecretKey signingKey = Jwts.SIG.HS384.key().build();