security - How to generate PublicKey from String Java -
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 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 @ sun.security.x509.x509key.decode(x509key.java:387) @ sun.security.x509.x509key.decode(x509key.java:403) @ sun.security.rsa.rsapublickeyimpl.<init>(rsapublickeyimpl.java:84) @ sun.security.rsa.rsakeyfactory.generatepublic(rsakeyfactory.java:298) @ sun.security.rsa.rsakeyfactory.enginegeneratepublic(rsakeyfactory.java:201)
your key base64 encoded pem format. have remove strings first, decode , can use 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 data byte[] encodedpublickey = base64.decode(pubkeypem); x509encodedkeyspec spec = new x509encodedkeyspec(encodedpublickey); keyfactory kf = keyfactory.getinstance("rsa"); system.out.println(kf.generatepublic(spec));
Comments
Post a Comment