Last active
November 13, 2020 12:29
-
-
Save bersling/4a7915837262f30588f9b670f172a44b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.security.KeyFactory | |
| import java.security.interfaces.RSAPublicKey | |
| import java.security.spec.X509EncodedKeySpec | |
| import java.util.Base64.getDecoder | |
| /* | |
| * Utility Method to convert a public key in the form of a string into a RSAPublicKey object. | |
| * Helpful for example for verifying JWT signatures! | |
| * */ | |
| fun convertPublicKeyStringToRSAPublicKey(publicKey: String): RSAPublicKey { | |
| // Clear the key of unwanted data, such that just the actual base64 key remains | |
| // (Yes, the stuff in those key files is actually base64!) | |
| val publicKeyContent: String = publicKey | |
| .replace("-----BEGIN PUBLIC KEY-----", "") | |
| .replace("-----END PUBLIC KEY-----", "") | |
| .replace("\n", "") | |
| // Decode the base64 key into a ByteArray | |
| val decodedKey: ByteArray = getDecoder().decode(publicKeyContent) | |
| // Generate the RSAPublicKey object from the decodedKey | |
| val keyFactory = KeyFactory.getInstance("RSA") | |
| val keySpecX509 = X509EncodedKeySpec(decodedKey) | |
| return keyFactory.generatePublic(keySpecX509) as RSAPublicKey | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment