PasswordRecipientInfoGenerator.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.Cms;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  12. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
  13. {
  14. internal class PasswordRecipientInfoGenerator : RecipientInfoGenerator
  15. {
  16. private static readonly CmsEnvelopedHelper Helper = CmsEnvelopedHelper.Instance;
  17. private AlgorithmIdentifier keyDerivationAlgorithm;
  18. private KeyParameter keyEncryptionKey;
  19. // TODO Can get this from keyEncryptionKey?
  20. private string keyEncryptionKeyOID;
  21. internal PasswordRecipientInfoGenerator()
  22. {
  23. }
  24. internal AlgorithmIdentifier KeyDerivationAlgorithm
  25. {
  26. set { this.keyDerivationAlgorithm = value; }
  27. }
  28. internal KeyParameter KeyEncryptionKey
  29. {
  30. set { this.keyEncryptionKey = value; }
  31. }
  32. internal string KeyEncryptionKeyOID
  33. {
  34. set { this.keyEncryptionKeyOID = value; }
  35. }
  36. public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
  37. {
  38. byte[] keyBytes = contentEncryptionKey.GetKey();
  39. string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID);
  40. IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName);
  41. // Note: In Java build, the IV is automatically generated in JCE layer
  42. int ivLength = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16;
  43. byte[] iv = new byte[ivLength];
  44. random.NextBytes(iv);
  45. ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv);
  46. keyWrapper.Init(true, new ParametersWithRandom(parameters, random));
  47. Asn1OctetString encryptedKey = new DerOctetString(
  48. keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));
  49. DerSequence seq = new DerSequence(
  50. new DerObjectIdentifier(keyEncryptionKeyOID),
  51. new DerOctetString(iv));
  52. AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(
  53. PkcsObjectIdentifiers.IdAlgPwriKek, seq);
  54. return new RecipientInfo(new PasswordRecipientInfo(
  55. keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey));
  56. }
  57. }
  58. }
  59. #pragma warning restore
  60. #endif