When to use X509EncodedKeySpec vs RSAPublicKeySpec?

23,443

There is a good summary of the common key formats here. As indicated by the javadocs for X509EncodedKeySpec this class is designed to convert between the SubjectPublicKeyInfo ASN.1 struct that is in the X.509 standard and Java public key formats. And since the first link indicated that a file of the form

-----BEGIN PUBLIC KEY-----
xxxx
xxxx
-----END PUBLIC KEY-----

is indeed a SubjectPublicKeyInfo, you are correctly parsing the file. There is one final step you're missing, and that's to convert your X509EncodedKeySpec into a public key. That is the function of the KeyFactory class. To extend your example by two more lines, it would be

KeyFactory kf = KeyFactory.getInstance("RSA"); // Assuming this is an RSA key
RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(publicKeySpec);
Share:
23,443
user3203425
Author by

user3203425

Updated on August 05, 2022

Comments

  • user3203425
    user3203425 almost 2 years

    I have a certificate in a text file, its contents look like:

    -----BEGIN PUBLIC KEY-----
    xxxx
    xxxx
    xxxx
    -----END PUBLIC KEY-----
    

    I believe this is a pem encoded certificate? So I want to load it now, I'm trying the following:

    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
        readFileToByteArray("keyfile"));
    

    but I get an InvalidKeySpecException.

    If I load the file, cut off the begin/end header/footer, then base64 decode the 'xxxx' contents, I don't get any complaints:

    String contents = readFileToString("keyfile");
    contents = contents.replace("-----BEGIN PUBLIC KEY-----", "");
    contents = contents.replace("-----END PUBLIC KEY-----", "");
    byte[] prepared = Base64.decode(contents);
    
    // ok.
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(prepared);
    

    is this the right way to load the key file? I see there's also a RSAPublicKeySpec class, which, based on the name, seems like something I'd be interested in here. But I believe it is only for generating certificates, not reading existing ones?

    Thanks