6

I have public key String

String publicK = "-----BEGIN PUBLIC KEY-----\n" +
    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgFhTDtuYJ5G5LEHMesnf\n" +
    "wX9cXZ1b/ozkkpbgtC3ziETiFkOFncbPCskpdbPmXxXv3vrwJ2RQIL2LZLZPe1xT\n" +
    "AyQY1DdD8hGqIemMwV2NqfFoEomVL5+QOAKCRiHkGgte6a2+OoTk9JzRP/NVaPkB\n" +
    "sdX1/nIPERYen3uDvUSYq83Ite2oDyaZZxj+/r46SadS/g5jWmeqgVoInJw813y7\n" +
    "Ee2HgYVbnktlLNhqIGj+1OKmwop+GP7Kk5CAkt9fo4VjRRllDaX1yFCZEbDL254n\n" +
    "S+LVOhl4mLBM8764+YVxjyYRC1Nq2rNZfQ602652i+l8u8nGqdiKOKDpjNDvhONP\n" +
    "yQIDAQAB\n" +
    "-----END PUBLIC KEY-----";

I want to convert PublicKey Object .

byte[] byteKey = publicK.getBytes();
X509EncodedKeySpec spec = new X509EncodedKeySpec(byteKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);

Above code throws exception

java.security.InvalidKeyException: invalid key format
at sun.security.x509.X509Key.decode(X509Key.java:387)
at sun.security.x509.X509Key.decode(X509Key.java:403)
at sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:84)
at sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:298)
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:201)
8
  • You are sure that your key is an RSA key? Commented Aug 18, 2017 at 10:22
  • What is publicK? Commented Aug 18, 2017 at 10:22
  • Yes. Its RSA key only Commented Aug 18, 2017 at 10:23
  • @Jens Reopened. Your 'duplicate' was about private keys. This is about public keys. Commented Aug 18, 2017 at 10:31
  • @Ejp but the Problem is the same. The key must be decoded! Commented Aug 18, 2017 at 10:32

1 Answer 1

10

Your key is a base64 encoded PEM Format. You have to remove the strings first, then decode it and then you can use the keyfactory.

    String publicK = "-----BEGIN PUBLIC KEY-----\n"
            + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgFhTDtuYJ5G5LEHMesnf\n"
            + "wX9cXZ1b/ozkkpbgtC3ziETiFkOFncbPCskpdbPmXxXv3vrwJ2RQIL2LZLZPe1xT\n"
            + "AyQY1DdD8hGqIemMwV2NqfFoEomVL5+QOAKCRiHkGgte6a2+OoTk9JzRP/NVaPkB\n"
            + "sdX1/nIPERYen3uDvUSYq83Ite2oDyaZZxj+/r46SadS/g5jWmeqgVoInJw813y7\n"
            + "Ee2HgYVbnktlLNhqIGj+1OKmwop+GP7Kk5CAkt9fo4VjRRllDaX1yFCZEbDL254n\n"
            + "S+LVOhl4mLBM8764+YVxjyYRC1Nq2rNZfQ602652i+l8u8nGqdiKOKDpjNDvhONP\n" + "yQIDAQAB\n"
            + "-----END PUBLIC KEY-----";

    String pubKeyPEM = publicK.replace("-----BEGIN PUBLIC KEY-----\n", "").replace("-----END PUBLIC KEY-----", "");

    // Base64 decode the data

    byte[] encodedPublicKey = Base64.decode(pubKeyPEM);

    X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedPublicKey);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    System.out.println(kf.generatePublic(spec));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.