Pkcs8EncryptedPrivateKeyInfoBuilder.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  10. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Pkcs
  11. {
  12. public class Pkcs8EncryptedPrivateKeyInfoBuilder
  13. {
  14. private PrivateKeyInfo privateKeyInfo;
  15. public Pkcs8EncryptedPrivateKeyInfoBuilder(byte[] privateKeyInfo): this(PrivateKeyInfo.GetInstance(privateKeyInfo))
  16. {
  17. }
  18. public Pkcs8EncryptedPrivateKeyInfoBuilder(PrivateKeyInfo privateKeyInfo)
  19. {
  20. this.privateKeyInfo = privateKeyInfo;
  21. }
  22. /// <summary>
  23. /// Create the encrypted private key info using the passed in encryptor.
  24. /// </summary>
  25. /// <param name="encryptor">The encryptor to use.</param>
  26. /// <returns>An encrypted private key info containing the original private key info.</returns>
  27. public Pkcs8EncryptedPrivateKeyInfo Build(
  28. ICipherBuilder encryptor)
  29. {
  30. try
  31. {
  32. MemoryStream bOut = new MemoryOutputStream();
  33. ICipher cOut = encryptor.BuildCipher(bOut);
  34. byte[] keyData = privateKeyInfo.GetEncoded();
  35. using (var str = cOut.Stream)
  36. {
  37. str.Write(keyData, 0, keyData.Length);
  38. }
  39. return new Pkcs8EncryptedPrivateKeyInfo(
  40. new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray()));
  41. }
  42. catch (IOException)
  43. {
  44. throw new InvalidOperationException("cannot encode privateKeyInfo");
  45. }
  46. }
  47. }
  48. }
  49. #pragma warning restore
  50. #endif