๐ Use Case:
When integrating with third-party platforms (e.g., Oracle Integration Cloud, REST APIs with JWT, or SAML), you often receive a certificate. To validate tokens or signatures, you must extract the RSA public key from an X.509 certificate file (like .cer
or .crt
).
✅ Solution Steps
๐ฝ Input:
- A
.cer
or.crt
file (Base64-encoded X.509 format) - Goal: Extract the RSA public key in readable format
๐ง Option 1: Using OpenSSL (Command Line)
๐ฅ Steps:
- Save your certificate as
cert.pem
(Base64 X.509 format). - Run this command:
openssl x509 -in cert.pem -pubkey -noout > public_key.pem
✅ Output:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQE...
-----END PUBLIC KEY-----
๐ Notes:
- Works on Linux/macOS/WSL/Windows with OpenSSL installed
- Easy to use in automation scripts
☕ Option 2: Using Java Code (Without OpenSSL)
๐ฅ Steps:
1. Convert .cer
File to Base64 Text:
- Open your
.cer
file (which is binary) in any Base64 encoder (e.g., PowerShell, online tool, or base64 CLI). - It should look like this:
-----BEGIN CERTIFICATE-----
MIIDczCCAlugAwIBAgIEXV...<trimmed>...C2s85w==
-----END CERTIFICATE-----
2. Copy Only the Certificate Key Part:
- Copy the middle Base64 key part (remove headers and newlines).
- Store it in a Java string like
base64Cert
in the code below.
✅ Java Code:
import java.io.ByteArrayInputStream;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
public class RSAPublicKeyExtractor {
public static void main(String[] args) throws Exception {
// Step 1: Paste your base64-encoded certificate string here
String base64Cert =
"MIIDczCCAlugAwIBAgIEXV...<full cert key here>...C2s85w==";
// Step 2: Decode the base64 string
byte[] certBytes = Base64.getDecoder().decode(base64Cert);
// Step 3: Convert to X.509 certificate
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certFactory
.generateCertificate(new ByteArrayInputStream(certBytes));
// Step 4: Extract public key
PublicKey publicKey = cert.getPublicKey();
// Step 5: Print the public key details
System.out.println("Public Key Algorithm : " + publicKey.getAlgorithm());
System.out.println("Public Key Format : " + publicKey.getFormat());
System.out.println("Public Key (Base64) : ");
System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
}
}
๐งพ Sample Output:
Public Key Algorithm : RSA
Public Key Format : X.509
Public Key (Base64) :
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArpM...
No comments:
Post a Comment