Search code examples
c#privatebouncycastlepublicecdh

Import public/private ECDH keys in BouncyCastle


I'm trying to import public and private ECDH keys in BouncyCastle. To import public key i use the C# code bellow and the code is works fine:

byte[] pc = HexStringToByteArray(PUBLIC_KEY);
var ecdp = TlsEccUtilities.GetParametersForNamedCurve(NamedCurve.secp256r1);
var basePoint = TlsEccUtilities.ValidateECPublicKey(TlsEccUtilities.DeserializeECPublicKey(null, ecdp, pc));
SubjectPublicKeyInfo subinfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(basePoint);
ECPublicKeyParameters publicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(subinfo);

public key: 042e3e5ccf6b9ab04be7a22f3faccfde73c87e87155394a34815408a896ca18a374dac669af3bf6220fc863767f4af47507c5bc221fc4a19874daf39b4074e3eb8

private key: be3f9bff87973356d04dad279e21535925c3656db011c9ae76b5a7f09ef8d9de

But i can't find a solution to import the private key. Colud you please help me with this issue?


Solution

  • Finlay i found a solution:

    // Import public key
    byte[] pc = HexStringToByteArray(PUBLIC_KEY);
    var ecdp = TlsEccUtilities.GetParametersForNamedCurve(NamedCurve.secp256r1);
    var basePoint = TlsEccUtilities.ValidateECPublicKey(TlsEccUtilities.DeserializeECPublicKey(null, ecdp, pc));
    SubjectPublicKeyInfo subinfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(basePoint);
    ECPublicKeyParameters publicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(subinfo);
    
    // Import private key
    BigInteger bi = new BigInteger(HexStringToByteArray(PRIVATE_KEY));
    ECPrivateKeyParameters privateKey = new ECPrivateKeyParameters(bi, publicKey.Parameters);