2017-07-19 1 views
0

Je voudrais un ECDSA AsymmetricCipherKeyPair que je génère en format hexadécimal. Les clés publiques et privées.C# - AsymmetricCipherKeyPair en hexadécimal

Maintenant, je fais ceci:

//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); 

Il doit y avoir un moyen plus facile d'obtenir la sortie hexadécimal.

Répondre

1

Pour la clé privée:

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

et le public:

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