<PackageReference Include="BouncyCastle.Cryptography" Version="2.7.0-beta.98" />

Pkcs8EncryptedPrivateKeyInfoBuilder

using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using System; using System.IO; namespace Org.BouncyCastle.Pkcs { public class Pkcs8EncryptedPrivateKeyInfoBuilder { private readonly PrivateKeyInfo m_privateKeyInfo; public Pkcs8EncryptedPrivateKeyInfoBuilder(byte[] privateKeyInfo) : this(PrivateKeyInfo.GetInstance(privateKeyInfo)) { } public Pkcs8EncryptedPrivateKeyInfoBuilder(PrivateKeyInfo privateKeyInfo) { if (privateKeyInfo == null) throw new ArgumentNullException("privateKeyInfo"); m_privateKeyInfo = privateKeyInfo; } public Pkcs8EncryptedPrivateKeyInfo Build(ICipherBuilder encryptor) { try { AlgorithmIdentifier encryptionAlgorithm = (AlgorithmIdentifier)encryptor.AlgorithmDetails; MemoryStream memoryStream = new MemoryStream(); using (Stream output = encryptor.BuildCipher(memoryStream).Stream) m_privateKeyInfo.EncodeTo(output); DerOctetString encryptedData = DerOctetString.WithContents(memoryStream.ToArray()); return new Pkcs8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo(encryptionAlgorithm, encryptedData)); } catch (IOException) { throw new InvalidOperationException("cannot encode privateKeyInfo"); } } } }