EncryptedPrivateKeyInfoFactory.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  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.Security;
  9. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
  10. {
  11. public sealed class EncryptedPrivateKeyInfoFactory
  12. {
  13. private EncryptedPrivateKeyInfoFactory()
  14. {
  15. }
  16. public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
  17. DerObjectIdentifier algorithm,
  18. char[] passPhrase,
  19. byte[] salt,
  20. int iterationCount,
  21. AsymmetricKeyParameter key)
  22. {
  23. return CreateEncryptedPrivateKeyInfo(
  24. algorithm.Id, passPhrase, salt, iterationCount,
  25. PrivateKeyInfoFactory.CreatePrivateKeyInfo(key));
  26. }
  27. public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
  28. string algorithm,
  29. char[] passPhrase,
  30. byte[] salt,
  31. int iterationCount,
  32. AsymmetricKeyParameter key)
  33. {
  34. return CreateEncryptedPrivateKeyInfo(
  35. algorithm, passPhrase, salt, iterationCount,
  36. PrivateKeyInfoFactory.CreatePrivateKeyInfo(key));
  37. }
  38. public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
  39. string algorithm,
  40. char[] passPhrase,
  41. byte[] salt,
  42. int iterationCount,
  43. PrivateKeyInfo keyInfo)
  44. {
  45. IBufferedCipher cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher;
  46. if (cipher == null)
  47. throw new Exception("Unknown encryption algorithm: " + algorithm);
  48. Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters(
  49. algorithm, salt, iterationCount);
  50. ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters(
  51. algorithm, passPhrase, pbeParameters);
  52. cipher.Init(true, cipherParameters);
  53. byte[] encoding = cipher.DoFinal(keyInfo.GetEncoded());
  54. DerObjectIdentifier oid = PbeUtilities.GetObjectIdentifier(algorithm);
  55. AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, pbeParameters);
  56. return new EncryptedPrivateKeyInfo(algID, encoding);
  57. }
  58. }
  59. }
  60. #pragma warning restore
  61. #endif