简体   繁体   中英

C# - AsymmetricCipherKeyPair to hexadecimal

I would like an ECDSA AsymmetricCipherKeyPair that I generate in hexadecimal format. Both the public and private keys.

Now I am doing this:

//Generate key pair
ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDSA");
SecureRandom secureRandom = new SecureRandom();
KeyGenerationParameters keyGenParam = new KeyGenerationParameters(secureRandom, keySize);
gen.Init(keyGenParam);
AsymmetricCipherKeyPair keys = gen.GenerateKeyPair();

//Create a PEM and then extract the BASE64 part
var key = keys.Private;
TextWriter textWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(textWriter);
pemWriter.WriteObject(key);
pemWriter.Writer.Flush();
string pem = textWriter.ToString();
var pem2 = pem.Split('\r').Skip(1).TakeWhile(i => !i.Contains("-----")).ToArray();
pem = string.Join("",pem2);

//BASE64 to byte[] to hex
byte[] bytes = Convert.FromBase64String(pem);
string hex = BitConverter.ToString(bytes);

There must be an easier way to get the hexadecimal output.

For the private key:

bytes = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private).ParsePrivateKey().GetDerEncoded();

and the public:

bytes = Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public).GetDerEncoded();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM