2020import com .onixbyte .security .KeyLoader ;
2121import com .onixbyte .security .exception .KeyLoadingException ;
2222
23+ import java .math .BigInteger ;
2324import java .security .KeyFactory ;
2425import java .security .NoSuchAlgorithmException ;
2526import java .security .interfaces .RSAPrivateKey ;
2627import java .security .interfaces .RSAPublicKey ;
2728import java .security .spec .InvalidKeySpecException ;
2829import java .security .spec .PKCS8EncodedKeySpec ;
30+ import java .security .spec .RSAPublicKeySpec ;
2931import java .security .spec .X509EncodedKeySpec ;
3032import java .util .Base64 ;
3133
4749public class RSAKeyLoader implements KeyLoader {
4850
4951 private final Base64 .Decoder decoder ;
52+
53+ private final Base64 .Decoder urlDecoder ;
54+
5055 private final KeyFactory keyFactory ;
5156
5257 /**
@@ -58,6 +63,7 @@ public class RSAKeyLoader implements KeyLoader {
5863 public RSAKeyLoader () {
5964 try {
6065 this .decoder = Base64 .getDecoder ();
66+ this .urlDecoder = Base64 .getUrlDecoder ();
6167 this .keyFactory = KeyFactory .getInstance ("RSA" );
6268 } catch (NoSuchAlgorithmException e ) {
6369 throw new KeyLoadingException (e );
@@ -133,4 +139,22 @@ public RSAPublicKey loadPublicKey(String pemKeyText) {
133139 throw new KeyLoadingException ("Key spec is invalid." , e );
134140 }
135141 }
142+
143+ @ Override
144+ public RSAPublicKey loadPublicKey (String modulus , String exponent ) {
145+ try {
146+ var _modulus = new BigInteger (1 , urlDecoder .decode (modulus ));
147+ var _exponent = new BigInteger (1 , urlDecoder .decode (exponent ));
148+
149+ var keySpec = new RSAPublicKeySpec (_modulus , _exponent );
150+ var kf = KeyFactory .getInstance ("RSA" );
151+ if (kf .generatePublic (keySpec ) instanceof RSAPublicKey rsaPublicKey ) {
152+ return rsaPublicKey ;
153+ } else {
154+ throw new KeyLoadingException ("Cannot generate RSA public key with given modulus and exponent." );
155+ }
156+ } catch (NoSuchAlgorithmException | InvalidKeySpecException e ) {
157+ throw new KeyLoadingException ("Cannot generate RSA public key with given modulus and exponent." , e );
158+ }
159+ }
136160}
0 commit comments