Search code examples
c#rsabouncycastle

How to read der file and convert to AsymmetricCipherKeyPair?


I have a der file 'text.der' that contains a DER-encoded key. I want read it and convert to an instance of AsymmetricCipherKeyPair from the Bouncycastle C# library (here are the javadocs for the Java version).

For example for a pem file, we have PemReader/Writer in bouncycastle and we can do it. How can I go from the encoded key in a file to an AsymmetricCipherKeyPair


Solution

  • Assuming its the usual binary format DER public key file, with the binary DER coding for the SubjectPublicKeyInfo structure (I think OpenSSL uses this for its DER output format), you can do:

    byte[] derKeyBytes = File.ReadAllBytes("text.der"); // read in the binary file
    
    // Decode the public key component
    AsymmetricKeyParameter publicKey =
        PublicKeyFactory.CreateKey(derKeyBytes);
    

    You're better of just using the AsymmetricKeyParameter (which is the public part of the key), but if you absolutely want it in a AsymmetricCipherKeyPair, you can do this:

    // Put the public key into a keyPair, leave the Private key uninitialized.
    AsymmetricCipherKeyPair keyPair =
        new AsymmetricCipherKeyPair(
            publicKey,
            new AsymmetricKeyParameter(true));