Java remove public key header and footer from string

Viewed 2097

Hi I am trying to remove the header and footer off a public key that is being stored as a string. I have managed to work out how to remove the "begin" header by removing everything up to the first "\n",

-----BEGIN PUBLIC KEY-----\n

with this code.

String s1 = pKey.substring(pKey.indexOf("\n")+1);

I am however struggling to remove the footer from the end up to the last "\n".

\n-----END PUBLIC KEY-----

There must be a cleaner way to remove them both.

3 Answers

You may use

String s1 = pKey.replaceAll("^.*\n|\n-+END PUBLIC KEY-+$", "");

Regex details

  • ^.*\n - start of string and the first line with a newline
  • | - or
  • \n-+END PUBLIC KEY-+$ - a newline char followed with 1+ - chars, then END PUBLIC KEY and then one or more hyphens till the end of the string.

Public key can be Some thing like this "-----BEGIN PUBLIC KEY----\nkey\n-----END PUBLIC KEY-----"

So to remove header and footer from string you can use pKey.substring(pKey.indexOf("\n")+1, pKey.lastIndexOf("\n"));

or other way just replace header and footer directly by empty , since it won't be present in key

I've been using the following util method to parse RSA public keys from text:

public static RSAPublicKey parsePKCS8PublicKey(String publicKey) {
    publicKey = publicKey
            .replace("-----BEGIN PUBLIC KEY-----", "")
            .replace("-----END PUBLIC KEY-----", "")
            .replace("\n", "")
            .trim();
    byte[] bytes = Base64.getDecoder().decode(publicKey);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    } catch (GeneralSecurityException e) {
        throw new IllegalArgumentException(e);
    }
}
Related