Java
Chilkat2 Java
Get RSA Key Modulus from .cer or .key
See more Certificates Examples
Demonstrates how to get the RSA key modulus from either the certificate (.cer) or RSA key (.key). OpenSSL commands to do the same would be:openssl x509 -inform DER -in "test.cer" -modulus -nooutor
openssl pkcs8 -inform DER -inβ "test.key"β -outform PEM -passin pass:"12345β678aβ" | openssl rsa -inform PEM -modulus -noout
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.PrivateKey;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.Xml;
public class ChilkatExample {
public static void main(String[] args) {
PrivateKey privKey = new PrivateKey();
String password = "12345678a";
try {
privKey.loadPkcs8EncryptedFile("qa_data/certs/test_12345678a.key", password);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
Xml xml = new Xml();
xml.loadXml(privKey.getXml());
// The XML contains the parts of the key in base64.
System.out.println("Private Key XML:");
System.out.println(xml.getXml());
// We can get the base64 modulus like this:
String modulus = xml.getChildContent("Modulus");
System.out.println("base64 modulus = " + modulus);
// To convert to hex:
BinData binDat = new BinData();
binDat.appendEncoded(modulus, "base64");
String hexModulus = binDat.getEncoded("hex");
System.out.println("hex modulus = " + hexModulus);
// Now get the modulus from the cert:
Cert cert = new Cert();
try {
cert.loadFromFile("qa_data/certs/test_12345678a.cer");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// The cert contains the public key, which is composed of the
// modulus + exponent (for RSA keys).
PublicKey pubKey = new PublicKey();
cert.getPublicKey(pubKey);
xml.loadXml(pubKey.getXml());
System.out.println("Public Key XML:");
System.out.println(xml.getXml());
// Proceed in the same way as before....
modulus = xml.getChildContent("Modulus");
System.out.println("base64 modulus = " + modulus);
// To convert to hex:
binDat.clear();
binDat.appendEncoded(modulus, "base64");
hexModulus = binDat.getEncoded("hex");
System.out.println("hex modulus = " + hexModulus);
}
}