Reputation: 754
I have a PublicKey
(java.security.PublicKey
).
I need to convert it into HEX string.
Like when you open certificate (on Windows for ex.) and look at Public Key information. You will see:
04 40 ad 77 10 45 08 f2 3a ae 1d 1d 95 22 2f b3 f5 e5 2f da db 8c 39 3a 03 15 fb 4b 36 28 46 de 7b 00 f4 73 11 ae b9 ac 00 aa 19 34 6d fb 7c 56 b1 93 c0 1b 86 7c d0 a2 0b 4d 22 a9 d2 4d b0 f6 34 c4
(*)
Any ideas how to do that?
EDIT:
I tried:
Hex.encodeHexString(cert.getPublicKey.getEncoded)
It returns me a string:
3063301c06062a8503020213301206072a85030202230106072a850302021e01034300_0440ad77104508f23aae1d1d95222fb3f5e52fdadb8c393a0315fb4b362846de7b00f47311aeb9ac00aa19346dfb7c56b193c01b867cd0a20b4d22a9d24db0f634c4
This string contains HEX value (*) (i placed _ where it starts).
Upvotes: 1
Views: 6723
Reputation: 799
You can use code below to get public key value in a representation same as windows.
PublicKey publicKey = ...;
String publickKeyHexValue = Hex.toHexString(publicKey.getEncoded());
ps: I used BouncyCastle
Library and in particular HEX
class in org.bouncycastle.util.encoders
package.
Upvotes: 0
Reputation: 94058
What you have in Java is called SubjectPublicKeyInfo
, which is indeed specified in the Java. You can view it online here. As we can see it is a Russian GOST Elliptic Curve public key. It contains the OID's (object identifiers) of the public key format, the Elliptic Curve domain parameters and the hash identifier.
As you can also see the value you get from Microsoft is a bit odd. The actual public key value is:
ad77104508f23aae1d1d95222fb3f5e52fdadb8c393a0315fb4b362846de7b00f47311aeb9ac00aa19346dfb7c56b193c01b867cd0a20b4d22a9d24db0f634c4
The 0440
just indicates that this value is encoded as an octet string (aka byte array). Even more precisely it's the point:
(78460489894733727260622807718072211860518873236604684346084533999519831849728, 110567644507038660207162091352707227223755109412227308137485312229644099269828)
on the 256 bit curve. You get these values by splitting the binary string precisely through the middel (either coordinate has the same size as the curve due to the way they are encoded).
Now if you want to get the public key value you can go (at least) two ways about it. Either you parse the bytes you get back from getEncoded
or you find out the actual type of your PublicKey
, cast it to that type, and then use the additional functionality of the specific class to retrieve information about the public key, such as the Elliptic Curve point.
Upvotes: 3