java - Convert certificate string to byte array -
i got string represents pem certificate:
-----begin certificate----- miicutccafugawibagibadanbgkqhkig9w0baqqfadbxmqswcqydvqqgewjdtjel makga1uecbmcue4xczajbgnvbactaknomqswcqydvqqkewjptjelmakga1uecxmc vu4xfdasbgnvbamtc0hlcm9uzybzyw5nmb4xdta1mdcxntixmtk0n1oxdta1mdgx ndixmtk0n1owvzelmakga1uebhmcq04xczajbgnvbagtalbomqswcqydvqqhewjd tjelmakga1uechmct04xczajbgnvbastalvomrqwegydvqqdewtizxjvbmcgwwfu zzbcma0gcsqgsib3dqebaquaa0samegcqqcp5hng7ogbhtlynpos21cbewke/b7j v14qeyslnr26xzussvko36znhiao/zbmoorckk9vecgmtclfuqtwdl3ragmbaagj gbewga4whqydvr0obbyeffxi70krxeqdxzgbacqor4judncemh8ga1udiwr4mhaa ffxi70krxeqdxzgbacqor4judnceovukwtbxmqswcqydvqqgewjdtjelmakga1ue cbmcue4xczajbgnvbactaknomqswcqydvqqkewjptjelmakga1uecxmcvu4xfdas bgnvbamtc0hlcm9uzybzyw5nggeamawga1udewqfmambaf8wdqyjkozihvcnaqee bqadqqa/ugzbrjjk9jcwndvfghlk3icnrq0ov7ri32z/+hqx67arfgzu7kwdi+ju wm7dcfrpngvwfwuqomspue9rzbgo -----end certificate-----
i assigned above string string variable string mycertstr
.
what proper way convert mycertstr
der encoded byte[]?
(i using java 7, , not interested use 3rd party library this, seeking jdk7 way of doing it.)
important
as @dave_thompson_085 has pointed out in comments, sunjce certificatefactory indeed capable of parsing pem files.
so can use certificate object detailed @ how load public certificate pem file..? (which earlier answer @dave on same topic, please upvote it, instead of one, if find useful !), , access encoded (der) form.
however, if pem file raw "rsa public key" (like 1 attached question), or other entity sunjce implementation can not parse directly, can still parse , decode manually, detailed below.
technically have here not certificate, public key.
you can decode der bytes simple that:
byte[] derbytes = base64.getdecoder().decode( pemtext.replaceall("-----(begin|end) rsa public key-----", "").replaceall("\n", "") );
note, raw rsa (pkcs#1) key:
rsapublickey ::= sequence { modulus integer, -- n publicexponent integer -- e }
you can use same technique decode x.509 certificates or private keys.
e.g. code decode x.509 certificate:
byte[] certificatebytes = base64.getdecoder().decode( pemtext.replaceall("-----(begin|end) certificate-----", "").replaceall("\n", "").getbytes("utf-8") ); certificatefactory certificatefactory = certificatefactory.getinstance("x.509"); x509certificate certificate = (x509certificate)(certificatefactory.generatecertificate( new bytearrayinputstream(certificatebytes) ) );
update
the code above uses java 8 base64 decoder. question has been updated asking java 7 solution, here link excellent thread, discussing various options available: base64 java encode , decode string.
e.g. java.xml.bind method described there not require libraries on java 7 (which seems match op wants)
Comments
Post a Comment