Pkcs8EncryptedPrivateKeyInfoBuilder.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  10. namespace BestHTTP.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. Stream str = cOut.Stream;
  36. str.Write(keyData, 0, keyData.Length);
  37. BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(str);
  38. return new Pkcs8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray()));
  39. }
  40. catch (IOException)
  41. {
  42. throw new InvalidOperationException("cannot encode privateKeyInfo");
  43. }
  44. }
  45. }
  46. }
  47. #pragma warning restore
  48. #endif