일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- ubuntu
- d3js
- vitejs
- Python
- EUREKA
- NextJS13
- loguru
- Vue3
- vuex
- 오라클
- nodejs
- springboot
- react
- JUnit
- svelte
- Vue
- Test
- NextJS
- Java
- Spring
- fastapi
- sveltekit
- Logging
- InteliJ
- Shell
- gradle
- npm
- fetch
- post
- style
- Today
- Total
양군의 행복한 이야기
openssl로 생성된 public key pem 파일 java로 읽어들이기 본문
일반 pem파일은 해더 + BASE64 인코딩 + 풋 이런식이다.
-----BEGIN RSA PUBLIC KEY-----
MIGJ......
-----END RSA PUBLIC KEY-----
그런데 이게 사이즈가 약간 다를때가 있다..
어떤 이유인진 모르겠지만 키를 생성시 옵션을 준듯하다.
(pem 방식이 아닌 der 방식을 base64로 인코딩한 것 ㅡㅡ)
이런경우 기존 방식 대로 읽어 들이면 invalied key라며 팅겨낸다.
FileInputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
KeySpec keySpec = new X509EncodedKeySpec(buffer);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey key = kf.generatePublic(keySpec);
이경우는 아래와 같은 방식으로 읽어 들어야 한다.
byte[] key = Base64.decodeBase64(Key);
ASN1InputStream in = new ASN1InputStream(key);
ASN1Primitive ob = in.readObject();
RSAPublicKeyStructure PsTRUCT = RSAPublicKeyStructure.getInstance(ob);
RSAPublicKeySpec spec = new RSAPublicKeySpec(PsTRUCT.getModulus(), PsTRUCT.getPublicExponent());
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pk = kf.generatePublic(spec);
라이블러리는 bouncycastle
이거 찾느라고 4일 걸렸다 ㅡㅡ