Beispiel #1
0
        private PopoPrivKey(Asn1TaggedObject obj)
        {
            this.tagNo = obj.TagNo;

            switch (tagNo)
            {
            case thisMessage:
                this.obj = DerBitString.GetInstance(obj, false);
                break;

            case subsequentMessage:
                this.obj = SubsequentMessage.ValueOf(DerInteger.GetInstance(obj, false).Value.IntValue);
                break;

            case dhMAC:
                this.obj = DerBitString.GetInstance(obj, false);
                break;

            case agreeMAC:
                this.obj = PKMacValue.GetInstance(obj, false);
                break;

            case encryptedKey:
                this.obj = EnvelopedData.GetInstance(obj, false);
                break;

            default:
                throw new ArgumentException("unknown tag in PopoPrivKey", "obj");
            }
        }
Beispiel #2
0
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

            EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

            //
            // read the recipients
            //
            Asn1Set recipientInfos = envData.RecipientInfos;

            //
            // read the encrypted content info
            //
            EncryptedContentInfo encInfo = envData.EncryptedContentInfo;

            this.encAlg = encInfo.ContentEncryptionAlgorithm;
            ICmsReadable      readable       = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
            CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsEnvelopedSecureReadable(
                this.encAlg, readable);

            //
            // build the RecipientInformationStore
            //
            this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
                recipientInfos, secureReadable);

            this.unprotectedAttributes = envData.UnprotectedAttrs;
        }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="x509_certificate2"></param>
        /// <param name="encrypted_data"></param>
        /// <returns></returns>
        public byte[] GetDecryptedContent(X509Certificate2 x509_certificate2, byte[] encrypted_data)
        {
            Org.BouncyCastle.Asn1.Cms.ContentInfo _content = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(Asn1Sequence.FromByteArray(encrypted_data));

            EnvelopedData _envelopedData = EnvelopedData.GetInstance(_content.Content);

            EncryptedContentInfo _encryptedContentInfo = _envelopedData.EncryptedContentInfo;

            byte[] _encrypt = _encryptedContentInfo.EncryptedContent.GetOctets();

            RecipientInfo         _recipientInfo         = RecipientInfo.GetInstance(_envelopedData.RecipientInfos[0]);
            KeyTransRecipientInfo _keyTransRecipientInfo = KeyTransRecipientInfo.GetInstance(_recipientInfo.Info);

            byte[] _byteEncryptedKey = _keyTransRecipientInfo.EncryptedKey.GetOctets();

            RSACryptoServiceProvider _rsaCrypto = (RSACryptoServiceProvider)x509_certificate2.PrivateKey;

            byte[] _randomKey = _rsaCrypto.Decrypt(_byteEncryptedKey, false);

            AlgorithmIdentifier _contentEncryptionAlgorithm = _encryptedContentInfo.ContentEncryptionAlgorithm;
            Asn1OctetString     _paramIV = Asn1OctetString.GetInstance(_contentEncryptionAlgorithm.Parameters);

            byte[] _initVector = _paramIV.GetOctets();

            tDESCrypto _cryptoService = new tDESCrypto(_randomKey, _initVector);

            return(_cryptoService.Decrypt(_encrypt));
        }
        /// <summary>Build the PKIArchiveControl using the passed in encryptor to encrypt its contents.</summary>
        /// <param name="contentEncryptor">a suitable content encryptor.</param>
        /// <returns>a PKIArchiveControl object.</returns>
        public PkiArchiveControl Build(ICipherBuilderWithKey contentEncryptor)
        {
            CmsEnvelopedData envContent = envGen.Generate(keyContent, contentEncryptor);
            EnvelopedData    envD       = EnvelopedData.GetInstance(envContent.ContentInfo.Content);

            return(new PkiArchiveControl(new PkiArchiveOptions(new EncryptedKey(envD))));
        }
Beispiel #5
0
        private PopoPrivKey(Asn1TaggedObject obj)
        {
            this.tagNo = obj.TagNo;
            switch (this.tagNo)
            {
            case 0:
                this.obj = DerBitString.GetInstance(obj, false);
                return;

            case 1:
                this.obj = SubsequentMessage.ValueOf(DerInteger.GetInstance(obj, false).Value.IntValue);
                return;

            case 2:
                this.obj = DerBitString.GetInstance(obj, false);
                return;

            case 3:
                this.obj = PKMacValue.GetInstance(obj, false);
                return;

            case 4:
                this.obj = EnvelopedData.GetInstance(obj, false);
                return;

            default:
                throw new ArgumentException("unknown tag in PopoPrivKey", "obj");
            }
        }
Beispiel #6
0
        private PopoPrivKey(Asn1TaggedObject obj)
        {
            //IL_0094: Unknown result type (might be due to invalid IL or missing references)
            tagNo = obj.TagNo;
            switch (tagNo)
            {
            case 0:
                this.obj = DerBitString.GetInstance(obj, isExplicit: false);
                break;

            case 1:
                this.obj = SubsequentMessage.ValueOf(DerInteger.GetInstance(obj, isExplicit: false).Value.IntValue);
                break;

            case 2:
                this.obj = DerBitString.GetInstance(obj, isExplicit: false);
                break;

            case 3:
                this.obj = PKMacValue.GetInstance(obj, isExplicit: false);
                break;

            case 4:
                this.obj = EnvelopedData.GetInstance(obj, explicitly: false);
                break;

            default:
                throw new ArgumentException("unknown tag in PopoPrivKey", "obj");
            }
        }
Beispiel #7
0
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

            EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

            //
            // read the encrypted content info
            //
            EncryptedContentInfo encInfo = envData.EncryptedContentInfo;

            this.encAlg = encInfo.ContentEncryptionAlgorithm;

            //
            // load the RecipientInfoStore
            //
            Asn1Set s     = envData.RecipientInfos;
            IList   infos = new ArrayList();

            byte[] contentOctets = encInfo.EncryptedContent.GetOctets();

            foreach (Asn1Encodable ae in s)
            {
                RecipientInfo info          = RecipientInfo.GetInstance(ae);
                MemoryStream  contentStream = new MemoryStream(contentOctets, false);

                object type = info.Info;

                if (type is KeyTransRecipientInfo)
                {
                    infos.Add(new KeyTransRecipientInformation(
                                  (KeyTransRecipientInfo)type, encAlg, contentStream));
                }
                else if (type is KekRecipientInfo)
                {
                    infos.Add(new KekRecipientInformation(
                                  (KekRecipientInfo)type, encAlg, contentStream));
                }
                else if (type is KeyAgreeRecipientInfo)
                {
                    infos.Add(new KeyAgreeRecipientInformation(
                                  (KeyAgreeRecipientInfo)type, encAlg, contentStream));
                }
                else if (type is PasswordRecipientInfo)
                {
                    infos.Add(new PasswordRecipientInformation(
                                  (PasswordRecipientInfo)type, encAlg, contentStream));
                }
            }

            this.recipientInfoStore    = new RecipientInformationStore(infos);
            this.unprotectedAttributes = envData.UnprotectedAttrs;
        }
Beispiel #8
0
        private Asn1Object CreateDERForRecipient(byte[] @in, X509Certificate cert)
        {
            EncryptionUtils.DERForRecipientParams parameters = EncryptionUtils.CalculateDERForRecipientParams(@in);
            KeyTransRecipientInfo keytransrecipientinfo      = ComputeRecipientInfo(cert, parameters.abyte0);
            DerOctetString        deroctetstring             = new DerOctetString(parameters.abyte1);
            DerSet derset = new DerSet(new RecipientInfo(keytransrecipientinfo));
            EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data
                                                                                 , parameters.algorithmIdentifier, deroctetstring);
            EnvelopedData env         = new EnvelopedData(null, derset, encryptedcontentinfo, (Asn1Set)null);
            ContentInfo   contentinfo = new ContentInfo(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.EnvelopedData,
                                                        env);

            return(contentinfo.ToAsn1Object());
        }
Beispiel #9
0
        public CmsEnvelopedData(ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;
            EnvelopedData        instance             = EnvelopedData.GetInstance(contentInfo.Content);
            Asn1Set              recipientInfos       = instance.RecipientInfos;
            EncryptedContentInfo encryptedContentInfo = instance.EncryptedContentInfo;

            encAlg = encryptedContentInfo.ContentEncryptionAlgorithm;
            CmsReadable       readable       = new CmsProcessableByteArray(encryptedContentInfo.EncryptedContent.GetOctets());
            CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsEnvelopedSecureReadable(encAlg, readable);

            recipientInfoStore    = CmsEnvelopedHelper.BuildRecipientInformationStore(recipientInfos, secureReadable);
            unprotectedAttributes = instance.UnprotectedAttrs;
        }
        private Asn1Encodable CreateDERForRecipient(byte[] inp, X509Certificate cert)
        {
            string algorithm = PkcsObjectIdentifiers.RC2Cbc.Id;
            Pkcs12ParametersGenerator apg;
            CipherKeyGenerator        keygen;
            IBufferedCipher           cipher;

            try
            {
                apg    = new Pkcs12ParametersGenerator(new Sha1Digest());//TODO Check
                keygen = GeneratorUtilities.GetKeyGenerator(algorithm);
                cipher = CipherUtilities.GetCipher(algorithm);
            }
            catch (Exception e)
            {
                // happens when using the command line app .jar file
                throw new IOException("Could not find a suitable javax.crypto provider for algorithm " +
                                      algorithm + "; possible reason: using an unsigned .jar file", e);
            }

            //TODO apg.Init(PbeParametersGenerator.Pkcs12PasswordToBytes(password), salt, iCount);

            var parameters = apg.GenerateDerivedParameters(algorithm, inp.Length * 8);

            Asn1Encodable obj = null;

            //TODO
            //using (Asn1InputStream input = new Asn1InputStream(parameters.getEncoded("ASN.1")))
            //{
            //    obj = input.ReadObject();
            //}

            keygen.Init(new KeyGenerationParameters(new SecureRandom(), 128));
            var secretkey = keygen.GenerateKey();

            //TODO cipher.Init(true, secretkey, parameters);
            byte[] bytes = cipher.DoFinal(inp);

            var recipientInfo = ComputeRecipientInfo(cert, secretkey);
            var set           = new DerSet(new RecipientInfo(recipientInfo));

            var algorithmId   = new AlgorithmIdentifier(new DerObjectIdentifier(algorithm), obj);
            var encryptedInfo = new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmId, new DerOctetString(bytes));
            var enveloped     = new EnvelopedData(null, set, encryptedInfo, (Asn1Set)null);

            var contentInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, enveloped);

            return(contentInfo.Content);
        }
Beispiel #11
0
 public static EncryptedKey GetInstance(object o)
 {
     if (o is EncryptedKey)
     {
         return((EncryptedKey)o);
     }
     if (o is Asn1TaggedObject)
     {
         return(new EncryptedKey(EnvelopedData.GetInstance((Asn1TaggedObject)o, explicitly: false)));
     }
     if (o is EncryptedValue)
     {
         return(new EncryptedKey((EncryptedValue)o));
     }
     return(new EncryptedKey(EncryptedValue.GetInstance(o)));
 }
        /// <summary>
        /// Return the enveloped data structure contained in this control.
        /// </summary>
        /// <returns>a CMSEnvelopedData object.</returns>
        public CmsEnvelopedData GetEnvelopedData()
        {
            try
            {
                EncryptedKey  encKey = EncryptedKey.GetInstance(pkiArchiveOptions.Value);
                EnvelopedData data   = Org.BouncyCastle.Asn1.Cms.EnvelopedData.GetInstance(encKey.Value);

                return(new CmsEnvelopedData(new ContentInfo(CmsObjectIdentifiers.EnvelopedData, data)));
            }
            catch (CmsException e)
            {
                throw new CrmfException("CMS parsing error: " + e.Message, e);
            }
            catch (Exception e)
            {
                throw new CrmfException("CRMF parsing error: " + e.Message, e);
            }
        }
Beispiel #13
0
 public static EncryptedKey GetInstance(object o)
 {
     if (o is EncryptedKey)
     {
         return (EncryptedKey)o;
     }
     else if (o is Asn1TaggedObject)
     {
         return new EncryptedKey(EnvelopedData.GetInstance((Asn1TaggedObject)o, false));
     }
     else if (o is EncryptedValue)
     {
         return new EncryptedKey((EncryptedValue)o);
     }
     else
     {
         return new EncryptedKey(EncryptedValue.GetInstance(o));
     }
 }
Beispiel #14
0
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

            try
            {
                EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

                if (envData.OriginatorInfo != null)
                {
                    originatorInfo = new OriginatorInformation(envData.OriginatorInfo);
                }

                //
                // read the recipients
                //
                Asn1Set recipientInfos = envData.RecipientInfos;

                //
                // read the encrypted content info
                //
                EncryptedContentInfo encInfo = envData.EncryptedContentInfo;
                this.encAlg = encInfo.ContentEncryptionAlgorithm;
                CmsReadable        readable       = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
                ICmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsEnvelopedSecureReadable(
                    this.encAlg, readable);

                //
                // build the RecipientInformationStore
                //
                this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
                    recipientInfos, this.encAlg, secureReadable);

                this.unprotectedAttributes = envData.UnprotectedAttrs;
            }
            catch (Exception e)
            {
                throw new CmsException("malformed content", e);
            }
        }
Beispiel #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="x509_certificate2"></param>
        /// <param name="plain_data"></param>
        /// <returns></returns>
        public byte[] GetEncryptedContent(X509Certificate2 x509_certificate2, byte[] plain_data)
        {
            tDESCrypto _cryptoService = new tDESCrypto();

            // RecipientInfo 구조체 생성 및 설정
            RecipientInfo _recipientInfo = this.GetKeyTransRecipientInfo(x509_certificate2, _cryptoService.Key);

            // EncryptedContentInfo 구조체 생성 및 설정
            DerOctetString _taxInvoce = new DerOctetString(plain_data);

            byte[] _package = _taxInvoce.GetOctets();
            byte[] _encrypt = _cryptoService.Encrypt(_package);                       // 대칭키로 암호화
            EncryptedContentInfo _encryptedContentInfo = this.GetEncryptedContentInfo(_encrypt, _cryptoService.IV);

            // EnvelopedData 구조체 생성 및 설정
            Asn1Set       _receipientInfos = new DerSet(_recipientInfo);
            EnvelopedData _envelopedData   = new EnvelopedData((OriginatorInfo)null, _receipientInfos, _encryptedContentInfo, (Asn1Set)null);

            Org.BouncyCastle.Asn1.Cms.ContentInfo _content = new Org.BouncyCastle.Asn1.Cms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.3"), _envelopedData);
            return(_content.GetEncoded());
        }
Beispiel #16
0
        //-------------------------------------------------------------------------------------------------------------------------//
        //
        //-------------------------------------------------------------------------------------------------------------------------//

        /// <summary>
        /// RFC 3852 CMS 에 정의된 ContentInfo 구조체를 생성한다.
        /// </summary>
        /// <param name="x509_certificate2">랜덤키를 암호화하기 위한 공인인증서(국세청 공인인증서)</param>
        /// <param name="plain_data">데이터</param>
        /// <returns></returns>
        public byte[] GetContentInfo(X509Certificate2 x509_certificate2, ArrayList plain_data)
        {
            tDESCrypto _cryptoService = new tDESCrypto();

            // RecipientInfo 구조체 생성 및 설정
            RecipientInfo _recipientInfo = this.GetKeyTransRecipientInfo(x509_certificate2, _cryptoService.Key);

            // EncryptedContentInfo 구조체 생성 및 설정
            byte[] _package = this.GetTaxInvoicePackage(plain_data);
            byte[] _encrypt = _cryptoService.Encrypt(_package);                       // 대칭키로 암호화
            EncryptedContentInfo _encryptedContentInfo = this.GetEncryptedContentInfo(_encrypt, _cryptoService.IV);

            // EnvelopedData 구조체 생성 및 설정
            Asn1Set       _asn1Set  = new DerSet(_recipientInfo);
            EnvelopedData _envelope = new EnvelopedData((OriginatorInfo)null, _asn1Set, _encryptedContentInfo, (Asn1Set)null);

            // RFC 3852의 구성 데이터인 SignedData, EnvelopedData, EncryptedData 등을 넣어주는 컨테이너인 ContentInfo 구조체를 생성 및 설정한다.
            // ContentInfo 구조체는 표준전자세금계산서 개발지침(v1.0)의 58페이지 참조
            Org.BouncyCastle.Asn1.Cms.ContentInfo _content = new Org.BouncyCastle.Asn1.Cms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.3"), _envelope);
            return(_content.GetEncoded());
        }
Beispiel #17
0
        private Asn1Object CreateDERForRecipient(byte[] inp, X509Certificate cert)
        {
            String s = "1.2.840.113549.3.2";

            byte[] outp = new byte[100];
            DerObjectIdentifier derob = new DerObjectIdentifier(s);

            byte[]          keyp = IVGenerator.GetIV(16);
            IBufferedCipher cf   = CipherUtilities.GetCipher(derob);
            KeyParameter    kp   = new KeyParameter(keyp);

            byte[]           iv  = IVGenerator.GetIV(cf.GetBlockSize());
            ParametersWithIV piv = new ParametersWithIV(kp, iv);

            cf.Init(true, piv);
            int len = cf.DoFinal(inp, outp, 0);

            byte[] abyte1 = new byte[len];
            System.Array.Copy(outp, 0, abyte1, 0, len);
            DerOctetString        deroctetstring        = new DerOctetString(abyte1);
            KeyTransRecipientInfo keytransrecipientinfo = ComputeRecipientInfo(cert, keyp);
            DerSet derset          = new DerSet(new RecipientInfo(keytransrecipientinfo));
            Asn1EncodableVector ev = new Asn1EncodableVector();

            ev.Add(new DerInteger(58));
            ev.Add(new DerOctetString(iv));
            DerSequence          seq = new DerSequence(ev);
            AlgorithmIdentifier  algorithmidentifier  = new AlgorithmIdentifier(derob, seq);
            EncryptedContentInfo encryptedcontentinfo =
                new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring);
            Asn1Set       set = null;
            EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);

            Org.BouncyCastle.Asn1.Cms.ContentInfo contentinfo =
                new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env);
            return(contentinfo.ToAsn1Object());
        }
Beispiel #18
0
        private Asn1Object createDerForRecipient(byte[] inp, X509Certificate cert)
        {
            var s = "1.2.840.113549.3.2";

            var outp  = new byte[100];
            var derob = new DerObjectIdentifier(s);
            var keyp  = IvGenerator.GetIv(16);
            var cf    = CipherUtilities.GetCipher(derob);
            var kp    = new KeyParameter(keyp);
            var iv    = IvGenerator.GetIv(cf.GetBlockSize());
            var piv   = new ParametersWithIV(kp, iv);

            cf.Init(true, piv);
            var len = cf.DoFinal(inp, outp, 0);

            var abyte1 = new byte[len];

            System.Array.Copy(outp, 0, abyte1, 0, len);
            var deroctetstring        = new DerOctetString(abyte1);
            var keytransrecipientinfo = computeRecipientInfo(cert, keyp);
            var derset = new DerSet(new RecipientInfo(keytransrecipientinfo));
            var ev     = new Asn1EncodableVector
            {
                new DerInteger(58),
                new DerOctetString(iv)
            };
            var seq = new DerSequence(ev);
            var algorithmidentifier  = new AlgorithmIdentifier(derob, seq);
            var encryptedcontentinfo =
                new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring);

            var env         = new EnvelopedData(null, derset, encryptedcontentinfo, (Asn1Set)null);
            var contentinfo =
                new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env);

            return(contentinfo.ToAsn1Object());
        }
Beispiel #19
0
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

            EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

            //
            // read the encrypted content info
            //
            EncryptedContentInfo encInfo = envData.EncryptedContentInfo;

            this.encAlg = encInfo.ContentEncryptionAlgorithm;

            //
            // load the RecipientInfoStore
            //
            byte[] contentOctets = encInfo.EncryptedContent.GetOctets();
            IList  infos         = CmsEnvelopedHelper.ReadRecipientInfos(
                envData.RecipientInfos, contentOctets, encAlg, null, null);

            this.recipientInfoStore    = new RecipientInformationStore(infos);
            this.unprotectedAttributes = envData.UnprotectedAttrs;
        }
Beispiel #20
0
        private ITestResult EnvelopedTest()
        {
            try
            {
                // Key trans
                ContentInfo info = ContentInfo.GetInstance(
                    Asn1Object.FromByteArray(envDataKeyTrns));
                EnvelopedData envData = EnvelopedData.GetInstance(info.Content);
                Asn1Set       s       = envData.RecipientInfos;

                if (s.Count != 1)
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong number of recipients"));
                }

                RecipientInfo recip = RecipientInfo.GetInstance(s[0]);

                if (recip.Info is KeyTransRecipientInfo)
                {
                    KeyTransRecipientInfo inf = KeyTransRecipientInfo.GetInstance(recip.Info);

                    inf = new KeyTransRecipientInfo(inf.RecipientIdentifier, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);

                    s = new DerSet(new RecipientInfo(inf));
                }
                else
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong recipient type"));
                }

                envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
                info    = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);

                if (!Arrays.AreEqual(info.GetEncoded(), envDataKeyTrns))
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped failed to re-encode"));
                }


                // KEK
                info = ContentInfo.GetInstance(
                    Asn1Object.FromByteArray(envDataKEK));
                envData = EnvelopedData.GetInstance(info.Content);
                s       = envData.RecipientInfos;

                if (s.Count != 1)
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong number of recipients"));
                }

                recip = RecipientInfo.GetInstance(s[0]);

                if (recip.Info is KekRecipientInfo)
                {
                    KekRecipientInfo inf = KekRecipientInfo.GetInstance(recip.Info);

                    inf = new KekRecipientInfo(inf.KekID, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);

                    s = new DerSet(new RecipientInfo(inf));
                }
                else
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong recipient type"));
                }

                envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
                info    = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);

                if (!Arrays.AreEqual(info.GetEncoded(), envDataKEK))
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped failed to re-encode"));
                }

                // Nested NDEF problem
                Asn1StreamParser    asn1In = new Asn1StreamParser(new MemoryStream(envDataNestedNDEF, false));
                ContentInfoParser   ci     = new ContentInfoParser((Asn1SequenceParser)asn1In.ReadObject());
                EnvelopedDataParser ed     = new EnvelopedDataParser((Asn1SequenceParser)ci
                                                                     .GetContent(Asn1Tags.Sequence));
                Touch(ed.Version);
                ed.GetOriginatorInfo();
                ed.GetRecipientInfos().ToAsn1Object();
                EncryptedContentInfoParser eci = ed.GetEncryptedContentInfo();
                Touch(eci.ContentType);
                Touch(eci.ContentEncryptionAlgorithm);

                Stream dataIn = ((Asn1OctetStringParser)eci.GetEncryptedContent(Asn1Tags.OctetString))
                                .GetOctetStream();
                Streams.Drain(dataIn);
                dataIn.Close();

                // Test data doesn't have unprotected attrs, bug was being thrown by this call
                Asn1SetParser upa = ed.GetUnprotectedAttrs();
                if (upa != null)
                {
                    upa.ToAsn1Object();
                }

                return(new SimpleTestResult(true, Name + ": Okay"));
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false, Name + ": CMS enveloped failed - " + e.ToString(), e));
            }
        }
Beispiel #21
0
        public MimeEntity DecryptEntity(byte[] encryptedBytes, X509Certificate2 decryptingCertificate)
        {
            try
            {
                if (decryptingCertificate == null)
                {
                    throw new EncryptionException(EncryptionError.NoCertificates);
                }

                // TODO: introduce buffering if you are using large files
                // CMSEnvelopeData is a PKCS# structure  rfc4134
                var envelopedData = new CmsEnvelopedData(encryptedBytes);
                var envData       = EnvelopedData.GetInstance(envelopedData.ContentInfo.Content);

                using (var session = GetSession())
                {
                    if (session == null)
                    {
                        return(null);
                    }

                    foreach (Asn1Sequence asn1Set in envData.RecipientInfos)
                    {
                        var recip = RecipientInfo.GetInstance(asn1Set);
                        var keyTransRecipientInfo = KeyTransRecipientInfo.GetInstance(recip.Info);

                        var sessionKey = Pkcs11Util.Decrypt(session, keyTransRecipientInfo, decryptingCertificate);

#if DEBUG
                        Console.WriteLine(Asn1Dump.DumpAsString(envData));
#endif
                        if (sessionKey == null)
                        {
                            continue;
                        }

                        var recipientId           = new RecipientID();
                        var issuerAndSerialNumber = (IssuerAndSerialNumber)keyTransRecipientInfo.RecipientIdentifier.ID;
                        recipientId.Issuer       = issuerAndSerialNumber.Name;
                        recipientId.SerialNumber = issuerAndSerialNumber.SerialNumber.Value;
                        var recipientInformation = envelopedData.GetRecipientInfos().GetRecipients(recipientId);
                        var recipients           = new ArrayList(recipientInformation);

                        //
                        // read the encrypted content info
                        //
                        var encInfo      = envData.EncryptedContentInfo;
                        var encAlg       = encInfo.ContentEncryptionAlgorithm;
                        var readable     = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
                        var keyParameter = ParameterUtilities.CreateKeyParameter(encAlg.Algorithm.Id, sessionKey);

                        // Todo: does this work with multi recipient?
                        foreach (RecipientInformation recipient in recipients)
                        {
                            var cmsReadable    = GetReadable(keyParameter, encAlg, readable);
                            var cmsTypedStream = new CmsTypedStream(cmsReadable.GetInputStream());
                            var contentBytes   = StreamToByteArray(cmsTypedStream.ContentStream);
                            var mimeEntity     = MimeSerializer.Default.Deserialize <MimeEntity>(contentBytes);
                            return(mimeEntity);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error.NotifyEvent(this, ex);
            }

            return(null);
        }
Beispiel #22
0
 public EncryptedKey(EnvelopedData envelopedData)
 {
     this.envelopedData = envelopedData;
 }