# After using GenerateAsymmetricKeyPair[], how to print the two keys in hex?

After using GenerateAsymmetricKeyPair in Mathematica 12, how can I print the two keys in hex?

There is probably a simple answer that I'm missing, but there's nothing about this in the documentation for GenerateAsymmetricKeyPair.

I think BaseEncode is the most direct way to convert the ByteArray to a hex string. For example, to get the public key in hex:

pair = GenerateAsymmetricKeyPair[]
BaseEncode[
pair["PublicKey"]["PublicByteArray"],
"Base16"
]


The same will work for pair["PrivateKey"]["PrivateByteArray"]

# Edit

It seems like 2-argument BaseEncode is not supported in V12.0. You can use the following instead:

ToUpperCase @ StringJoin[
Map[IntegerString[#, 16, 2]&,
ImportByteArray[pair["PublicKey"]["PublicByteArray"], "Byte"]
]
]

• Thanks for this. But it's telling me BaseEncode::argx: BaseEncode called with 2 arguments; 1 argument is expected. I've no idea why this is. The documentation says BaseEncode should be able to take a specification of the required coding as its second argument. Perhaps this is new to 12.2? I'm using 12.0.
– ool
Mar 18 at 21:32
• @ool That's a shame. See the updated answer for a method that should work in V12.0. Mar 19 at 8:29
• Thanks, @SjoerdSmit - that works fine. Many thanks for your help. Now I will post another question about how to extract a fingerprint, also in hex.
– ool
Mar 19 at 11:33
• I'm putting this in a comment because it's maybe not suitable for a separate q, but when I specify a 4kbit key by using GenerateAsymmetricKeyPair[ Method -> <|"Type" -> "RSA", "KeySize" -> 4096|>], your code prints a string of length 1k hex chars ~ 0.5kB ~ 4kb which is correct for the public key in the strict sense but not for the key block which should contain some other info too (e.g. I have a 4kb pubkey with a block of length amost 12kb). Is there a way to get Mma to print a whole key block? gpg4win is refusing to import an ASCII file containing only the 0.5k printed hex chars.
– ool
Mar 19 at 23:10
• @ool There is no built-in functionality for this. If you can specify how the gpg4win key block should be generated, please detail it in a new question and me or someone else can probably help you. I don't know the implementation details myself. Mar 21 at 19:46