using System; using System.IO; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Pkcs { /// /// A holding class for a PKCS#8 encrypted private key info object that allows for its decryption. /// public class Pkcs8EncryptedPrivateKeyInfo { private EncryptedPrivateKeyInfo encryptedPrivateKeyInfo; private static EncryptedPrivateKeyInfo parseBytes(byte[] pkcs8Encoding) { try { return EncryptedPrivateKeyInfo.GetInstance(pkcs8Encoding); } catch (ArgumentException e) { throw new PkcsIOException("malformed data: " + e.Message, e); } catch (Exception e) { throw new PkcsIOException("malformed data: " + e.Message, e); } } /// /// Base constructor from a PKCS#8 EncryptedPrivateKeyInfo object. /// /// A PKCS#8 EncryptedPrivateKeyInfo object. public Pkcs8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) { this.encryptedPrivateKeyInfo = encryptedPrivateKeyInfo; } /// /// Base constructor from a BER encoding of a PKCS#8 EncryptedPrivateKeyInfo object. /// /// A BER encoding of a PKCS#8 EncryptedPrivateKeyInfo objects. public Pkcs8EncryptedPrivateKeyInfo(byte[] encryptedPrivateKeyInfo) : this(parseBytes(encryptedPrivateKeyInfo)) { } /// /// Returns the underlying ASN.1 structure inside this object. /// /// Return the EncryptedPrivateKeyInfo structure in this object. public EncryptedPrivateKeyInfo ToAsn1Structure() { return encryptedPrivateKeyInfo; } /// /// Returns a copy of the encrypted data in this structure. /// /// Return a copy of the encrypted data in this object. public byte[] GetEncryptedData() { return encryptedPrivateKeyInfo.GetEncryptedData(); } /// /// Return a binary ASN.1 encoding of the EncryptedPrivateKeyInfo structure in this object. /// /// A byte array containing the encoded object. public byte[] GetEncoded() { return encryptedPrivateKeyInfo.GetEncoded(); } /// /// Get a decryptor from the passed in provider and decrypt the encrypted private key info, returning the result. /// /// A provider to query for decryptors for the object. /// The decrypted private key info structure. public PrivateKeyInfo DecryptPrivateKeyInfo(IDecryptorBuilderProvider inputDecryptorProvider) { try { ICipherBuilder decryptorBuilder = inputDecryptorProvider.CreateDecryptorBuilder(encryptedPrivateKeyInfo.EncryptionAlgorithm); ICipher encIn = decryptorBuilder.BuildCipher(new MemoryInputStream(encryptedPrivateKeyInfo.GetEncryptedData())); byte[] data; using (var strm = encIn.Stream) { data = Streams.ReadAll(encIn.Stream); } return PrivateKeyInfo.GetInstance(data); } catch (Exception e) { throw new PkcsException("unable to read encrypted data: " + e.Message, e); } } } }