From 5de7d8adee7d6cc4edd20dd52d1d7d558067ea35 Mon Sep 17 00:00:00 2001 From: aeeazip Date: Sun, 2 Jul 2023 19:22:49 +0900 Subject: [PATCH] =?UTF-8?q?feat(#5)=20:=20PublicKey=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trothcam/feign/PublicKeyGenerator.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/main/java/trothly/trothcam/feign/PublicKeyGenerator.java diff --git a/src/main/java/trothly/trothcam/feign/PublicKeyGenerator.java b/src/main/java/trothly/trothcam/feign/PublicKeyGenerator.java new file mode 100644 index 0000000..fb7e149 --- /dev/null +++ b/src/main/java/trothly/trothcam/feign/PublicKeyGenerator.java @@ -0,0 +1,48 @@ +package trothly.trothcam.feign; + +import org.springframework.stereotype.Component; +import org.springframework.util.Base64Utils; +import trothly.trothcam.dto.auth.apple.ApplePublicKey; +import trothly.trothcam.dto.auth.apple.ApplePublicKeys; + +import java.math.BigInteger; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.RSAPublicKeySpec; +import java.util.Map; + +@Component +public class PublicKeyGenerator { + + private static final String SIGN_ALGORITHM_HEADER_KEY = "alg"; + private static final String KEY_ID_HEADER_KEY = "kid"; + private static final int POSITIVE_SIGN_NUMBER = 1; + + // Public Key 생성 + public PublicKey generatePublicKey(Map headers, ApplePublicKeys applePublicKeys) { + ApplePublicKey applePublicKey = + applePublicKeys.getMatchesKey(headers.get(SIGN_ALGORITHM_HEADER_KEY), headers.get(KEY_ID_HEADER_KEY)); + + return generatePublicKeyWithApplePublicKey(applePublicKey); + } + + // Public Key 속 정보로 Public Key 생성 + private PublicKey generatePublicKeyWithApplePublicKey(ApplePublicKey publicKey) { + byte[] nBytes = Base64Utils.decodeFromUrlSafeString(publicKey.getN()); + byte[] eBytes = Base64Utils.decodeFromUrlSafeString(publicKey.getE()); + + BigInteger n = new BigInteger(POSITIVE_SIGN_NUMBER, nBytes); + BigInteger e = new BigInteger(POSITIVE_SIGN_NUMBER, eBytes); + + RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(n, e); + + try { + KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getKty()); + return keyFactory.generatePublic(publicKeySpec); + } catch (NoSuchAlgorithmException | InvalidKeySpecException exception) { + throw new IllegalStateException("Apple OAuth 로그인 중 public key 생성에 문제가 발생했습니다."); + } + } +}