JWE Create / Parse
*JWT 관련 자세한 설명 생략
▷ Example
/**
* JWE Create / Parse
*
* ▶ JWE(JSON WEB ENCRYPTION)
* → 서버와 클라이언트 간 암호화된 데이터를 Token 화 한것
* → claim 암호화
*
* ▶ JWT(JSON WEB TOKEN)
* → JWS & JWE
* → 서버와 클라이언트 간 정보를 주고 받을때 Http request 헤더에 JSON 토큰을 넣은 후
* 별도의 인증 과정없이 헤더에 포함되어 있는 JWT정보를 통해 인증
* → 구성
* → Header : 토큰의 타입과 암호화 알고리즘
* → Payload : claim 정보를 포함( name : value ), 공개/비공개 설정 가능
* → registered claim : JWTClaimsSet 제공
* → public claim : 사용자 정의
* → private claim :
* → Signaure : PRIVATE KEY
* */
public static void jweExample() throws Exception {
/** JWE RSA KEYPAIR */
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
HashMap<String, String> rsaKeyPair = getKeypair();
final String publicKey = rsaKeyPair.get("publicKey");
final String privateKey = rsaKeyPair.get("privateKey");
/* Encryption Key */
final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
final RSAPublicKey rsaPublicKey = (RSAPublicKey)keyFactory.generatePublic(x509EncodedKeySpec);
final RSAEncrypter encryptionKey = new RSAEncrypter(rsaPublicKey);
/* Decryption Key */
final PKCS8EncodedKeySpec pKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
final RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyFactory.generatePrivate(pKCS8EncodedKeySpec);
final RSADecrypter rsaDecrypter = new RSADecrypter(rsaPrivateKey);
/** JWE Header */
JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256CBC_HS512);
/** JWE Payload (registered claim) */
JWTClaimsSet payload = new JWTClaimsSet.Builder()
.issuer("토큰 발급자")
.subject("토큰 제목")
.audience("토큰 대상자")
.expirationTime(new Date(new Date().getTime() + 1000*60)) // 토큰의 만료시간
.issueTime(new Date()) // 토큰이 발급된 시간
.jwtID(UUID.randomUUID().toString()) // JWT의 고유 식별자
.build();
System.out.println("> JWT Payload (registered claim) : " + payload.getClaims());
/** JWE Claim Encryption */
final EncryptedJWT encryptedJWE = new EncryptedJWT(header, payload);
encryptedJWE.encrypt(encryptionKey);
encryptedJWE.serialize();
System.out.println("> RESULT JWE : " + encryptedJWE.serialize());
/** Parse */
final EncryptedJWT decryptedJWE = EncryptedJWT.parse(encryptedJWE.serialize());
System.out.println("> JWE STATE : " + decryptedJWE.getState());
System.out.println("> ENCRYPTED : " + decryptedJWE.getJWTClaimsSet());
/* JWE Claim Decryption */
decryptedJWE.decrypt(rsaDecrypter);
System.out.println("> JWE STATE : " + decryptedJWE.getState());
System.out.println("> DECRYPTED : " + decryptedJWE.getJWTClaimsSet());
}
/*
결과 :
> JWT Payload (registered claim) :
{
iss = 토큰 발급자,
sub = 토큰 제목,
aud = [토큰 대상자],
exp = Fri Oct 21 16: 10: 03 KST 2022,
iat = Fri Oct 21 16: 09: 03 KST 2022,
jti = 2d326b73 - 9989 - 4fac - 98de - 90a775ec1579
}
> RESULT JWE :
eyJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIj
oiUlNBLU9BRVAtMjU2In0.ELTN-5lp5CjRGbm0Jd
xX_twciS5MXFVRIRAlxn7tkPVj0PcijmfQE7ovMl
Kx8kT6b7cTVcASrOWhJQdQ03SDszXzew-2Hg1pgc
mnFyzkOThTmxfYecQJBVbNPi0QkNNknk7v5vKU3I
2CLFyaGrssTjpUudoD_0SpigSs51J7qRPN70VT0i
o4ni0IwiOHxPTY55dJmbsXUYKzisqY1Eoj6nn-q9
cZz5Ms92SvuaXLEkxz7fNAOt4QyJKSWstwCy93eu
3l_jTF6xw1rO1gJ81i-3xb9nd_ZxNtpNQQM_lTL7
SeYxt2A01IoQj9rKulUwCLCIGs9Mr-ThE44ewHNp
g43Q.ZARSHNZ0Hi1Bd6gKxnVRPw.gxDmRHdqTbXa
6DIauWmvxejVgcmS1tSIp1L6S_9VNeQdpBYOYKyr
wlYVjJsqb7f9OvSQv_XWil7rhS--MQyTz4c8-sp9
HTRdiIuI55LMZsHJDaMtDIMTNxrRS9GSKUcTRQq8
R0TxhroEaOP8KlR1F5Dqg9MYhbRHUM7n1mtxl20k
YFBlyZPk2-vsNvTE5IKSk4zEJ430WEVOLmNx1ETx
ew.aZJOSchVsWWFsQoArsfqfYQNZpuG2CYIdnLJ-
XmMsFk
> JWE STATE : ENCRYPTED
> ENCRYPTED : null
> JWE STATE : DECRYPTED
> DECRYPTED :
{
"sub": "토큰 제목",
"aud": "토큰 대상자",
"iss": "토큰 발급자",
"exp": 1666336203,
"iat": 1666336143,
"jti": "2d326b73-9989-4fac-98de-90a775ec1579"
}
*/
▷ 관련 글
Create RSA Keypair(.pem)
RSA Keypair 생성 메소드 /** * RSA Keypair(.pem) Create Method */ public static HashMap getKeypair() { HashMap keypairMap = new HashMap(); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048);
coding-today.tistory.com
Create JWT(nimbus)
JWT 생성 메소드 *JWE *자세한 설명 생략 /** * JWT CREATE * * @return String */ public String JWTCreate() { String jwt = ""; try { /** JWE RSA KEYPAIR */ final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); /* Encryption Key */ final X509
coding-today.tistory.com
VERIFY JWT(nimbus)
JWT 검증 메소드 *JWE *자세한 설명 생략 /** * JWT VERIFY * * @param HttpServletRequest * @param resVO * @return CmmResVO */ public CmmResVO JWTVerify(HttpServletRequest req, CmmResVO resVO) { try { final String jwt = req.getHeader("Authorization
coding-today.tistory.com
'▶ Back-End > Java' 카테고리의 다른 글
SpringBoot에서 MQTT Client + WebFlux 구축 (0) | 2022.12.02 |
---|---|
SpringBoot JSP 설정 (0) | 2022.12.01 |
Create RSA Keypair(.pem) (0) | 2022.10.21 |
JWS Example(nimbus) (0) | 2022.10.20 |
Create UUID ver4 (0) | 2022.10.20 |
댓글