CalculatePbeMac() static private method

static private CalculatePbeMac ( DerObjectIdentifier oid, byte salt, int itCount, char password, bool wrongPkcs12Zero, byte data ) : byte[]
oid Org.BouncyCastle.Asn1.DerObjectIdentifier
salt byte
itCount int
password char
wrongPkcs12Zero bool
data byte
return byte[]
        public static byte[] ConvertToDefiniteLength(byte[] berPkcs12File, char[] passwd)
        {
            //IL_00e8: Unknown result type (might be due to invalid IL or missing references)
            Pfx             pfx        = new Pfx(Asn1Sequence.GetInstance(Asn1Object.FromByteArray(berPkcs12File)));
            ContentInfo     authSafe   = pfx.AuthSafe;
            Asn1OctetString instance   = Asn1OctetString.GetInstance(authSafe.Content);
            Asn1Object      asn1Object = Asn1Object.FromByteArray(instance.GetOctets());

            authSafe = new ContentInfo(authSafe.ContentType, new DerOctetString(asn1Object.GetEncoded("DER")));
            MacData macData = pfx.MacData;

            try
            {
                int    intValue             = macData.IterationCount.IntValue;
                byte[] octets               = Asn1OctetString.GetInstance(authSafe.Content).GetOctets();
                byte[] digest               = Pkcs12Store.CalculatePbeMac(macData.Mac.AlgorithmID.Algorithm, macData.GetSalt(), intValue, passwd, wrongPkcs12Zero: false, octets);
                AlgorithmIdentifier algID   = new AlgorithmIdentifier(macData.Mac.AlgorithmID.Algorithm, DerNull.Instance);
                DigestInfo          digInfo = new DigestInfo(algID, digest);
                macData = new MacData(digInfo, macData.GetSalt(), intValue);
            }
            catch (global::System.Exception ex)
            {
                throw new IOException("error constructing MAC: " + ex.ToString());
            }
            pfx = new Pfx(authSafe, macData);
            return(pfx.GetEncoded("DER"));
        }
Beispiel #2
0
        public static byte[] ConvertToDefiniteLength(byte[] berPkcs12File, char[] passwd)
        {
            Pfx             pfx         = new Pfx(Asn1Sequence.GetInstance(Asn1Object.FromByteArray(berPkcs12File)));
            ContentInfo     contentInfo = pfx.AuthSafe;
            Asn1OctetString instance    = Asn1OctetString.GetInstance(contentInfo.Content);
            Asn1Object      asn1Object  = Asn1Object.FromByteArray(instance.GetOctets());

            contentInfo = new ContentInfo(contentInfo.ContentType, new DerOctetString(asn1Object.GetEncoded("DER")));
            MacData macData = pfx.MacData;

            try
            {
                int    intValue             = macData.IterationCount.IntValue;
                byte[] octets               = Asn1OctetString.GetInstance(contentInfo.Content).GetOctets();
                byte[] digest               = Pkcs12Store.CalculatePbeMac(macData.Mac.AlgorithmID.ObjectID, macData.GetSalt(), intValue, passwd, false, octets);
                AlgorithmIdentifier algID   = new AlgorithmIdentifier(macData.Mac.AlgorithmID.ObjectID, DerNull.Instance);
                DigestInfo          digInfo = new DigestInfo(algID, digest);
                macData = new MacData(digInfo, macData.GetSalt(), intValue);
            }
            catch (Exception ex)
            {
                throw new IOException("error constructing MAC: " + ex.ToString());
            }
            pfx = new Pfx(contentInfo, macData);
            return(pfx.GetEncoded("DER"));
        }
Beispiel #3
0
        /**
         * Re-encode the PKCS#12 structure to definite length encoding at the inner layer
         * as well, recomputing the MAC accordingly.
         *
         * @param berPKCS12File - original PKCS12 file.
         * @param provider - provider to use for MAC calculation.
         * @return a byte array representing the DER encoding of the PFX structure.
         * @throws IOException on parsing, encoding errors.
         */
        public static byte[] ConvertToDefiniteLength(
            byte[]  berPkcs12File,
            char[]  passwd)
        {
            Pfx pfx = new Pfx(Asn1Sequence.GetInstance(Asn1Object.FromByteArray(berPkcs12File)));

            ContentInfo info = pfx.AuthSafe;

            Asn1OctetString content = Asn1OctetString.GetInstance(info.Content);
            Asn1Object      obj     = Asn1Object.FromByteArray(content.GetOctets());

            info = new ContentInfo(info.ContentType, new DerOctetString(obj.GetEncoded(Asn1Encodable.Der)));

            MacData mData = pfx.MacData;

            try
            {
                int    itCount = mData.IterationCount.IntValue;
                byte[] data    = Asn1OctetString.GetInstance(info.Content).GetOctets();
                byte[] res     = Pkcs12Store.CalculatePbeMac(
                    mData.Mac.AlgorithmID.ObjectID, mData.GetSalt(), itCount, passwd, false, data);

                AlgorithmIdentifier algId = new AlgorithmIdentifier(
                    mData.Mac.AlgorithmID.ObjectID, DerNull.Instance);
                DigestInfo dInfo = new DigestInfo(algId, res);

                mData = new MacData(dInfo, mData.GetSalt(), itCount);
            }
            catch (Exception e)
            {
                throw new IOException("error constructing MAC: " + e.ToString());
            }

            pfx = new Pfx(info, mData);

            return(pfx.GetEncoded(Asn1Encodable.Der));
        }
Beispiel #4
0
        public void Save(Stream stream, char[] password, SecureRandom random)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (random == null)
            {
                throw new ArgumentNullException("random");
            }
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]);

            foreach (string text in this.keys.Keys)
            {
                byte[] array = new byte[20];
                random.NextBytes(array);
                AsymmetricKeyEntry  asymmetricKeyEntry = (AsymmetricKeyEntry)this.keys[text];
                DerObjectIdentifier oid;
                Asn1Encodable       asn1Encodable;
                if (password == null)
                {
                    oid           = PkcsObjectIdentifiers.KeyBag;
                    asn1Encodable = PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricKeyEntry.Key);
                }
                else
                {
                    oid           = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag;
                    asn1Encodable = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(this.keyAlgorithm, password, array, 1024, asymmetricKeyEntry.Key);
                }
                Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(new Asn1Encodable[0]);
                foreach (string text2 in asymmetricKeyEntry.BagAttributeKeys)
                {
                    Asn1Encodable obj = asymmetricKeyEntry[text2];
                    if (!text2.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        asn1EncodableVector2.Add(new Asn1Encodable[]
                        {
                            new DerSequence(new Asn1Encodable[]
                            {
                                new DerObjectIdentifier(text2),
                                new DerSet(obj)
                            })
                        });
                    }
                }
                asn1EncodableVector2.Add(new Asn1Encodable[]
                {
                    new DerSequence(new Asn1Encodable[]
                    {
                        PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                        new DerSet(new DerBmpString(text))
                    })
                });
                if (asymmetricKeyEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry   certificate = this.GetCertificate(text);
                    AsymmetricKeyParameter publicKey   = certificate.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   obj2        = Pkcs12Store.CreateSubjectKeyID(publicKey);
                    asn1EncodableVector2.Add(new Asn1Encodable[]
                    {
                        new DerSequence(new Asn1Encodable[]
                        {
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(obj2)
                        })
                    });
                }
                asn1EncodableVector.Add(new Asn1Encodable[]
                {
                    new SafeBag(oid, asn1Encodable.ToAsn1Object(), new DerSet(asn1EncodableVector2))
                });
            }
            byte[]      derEncoded  = new DerSequence(asn1EncodableVector).GetDerEncoded();
            ContentInfo contentInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(derEncoded));

            byte[] array2 = new byte[20];
            random.NextBytes(array2);
            Asn1EncodableVector asn1EncodableVector3 = new Asn1EncodableVector(new Asn1Encodable[0]);
            Pkcs12PbeParams     pkcs12PbeParams      = new Pkcs12PbeParams(array2, 1024);
            AlgorithmIdentifier algorithmIdentifier  = new AlgorithmIdentifier(this.certAlgorithm, pkcs12PbeParams.ToAsn1Object());
            ISet set = new HashSet();

            foreach (string text3 in this.keys.Keys)
            {
                X509CertificateEntry certificate2        = this.GetCertificate(text3);
                CertBag             certBag              = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(certificate2.Certificate.GetEncoded()));
                Asn1EncodableVector asn1EncodableVector4 = new Asn1EncodableVector(new Asn1Encodable[0]);
                foreach (string text4 in certificate2.BagAttributeKeys)
                {
                    Asn1Encodable obj3 = certificate2[text4];
                    if (!text4.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        asn1EncodableVector4.Add(new Asn1Encodable[]
                        {
                            new DerSequence(new Asn1Encodable[]
                            {
                                new DerObjectIdentifier(text4),
                                new DerSet(obj3)
                            })
                        });
                    }
                }
                asn1EncodableVector4.Add(new Asn1Encodable[]
                {
                    new DerSequence(new Asn1Encodable[]
                    {
                        PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                        new DerSet(new DerBmpString(text3))
                    })
                });
                if (certificate2[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    AsymmetricKeyParameter publicKey2 = certificate2.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   obj4       = Pkcs12Store.CreateSubjectKeyID(publicKey2);
                    asn1EncodableVector4.Add(new Asn1Encodable[]
                    {
                        new DerSequence(new Asn1Encodable[]
                        {
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(obj4)
                        })
                    });
                }
                asn1EncodableVector3.Add(new Asn1Encodable[]
                {
                    new SafeBag(PkcsObjectIdentifiers.CertBag, certBag.ToAsn1Object(), new DerSet(asn1EncodableVector4))
                });
                set.Add(certificate2.Certificate);
            }
            foreach (string text5 in this.certs.Keys)
            {
                X509CertificateEntry x509CertificateEntry = (X509CertificateEntry)this.certs[text5];
                if (this.keys[text5] == null)
                {
                    CertBag             certBag2             = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(x509CertificateEntry.Certificate.GetEncoded()));
                    Asn1EncodableVector asn1EncodableVector5 = new Asn1EncodableVector(new Asn1Encodable[0]);
                    foreach (string text6 in x509CertificateEntry.BagAttributeKeys)
                    {
                        if (!text6.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                        {
                            Asn1Encodable obj5 = x509CertificateEntry[text6];
                            if (!text6.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                            {
                                asn1EncodableVector5.Add(new Asn1Encodable[]
                                {
                                    new DerSequence(new Asn1Encodable[]
                                    {
                                        new DerObjectIdentifier(text6),
                                        new DerSet(obj5)
                                    })
                                });
                            }
                        }
                    }
                    asn1EncodableVector5.Add(new Asn1Encodable[]
                    {
                        new DerSequence(new Asn1Encodable[]
                        {
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(text5))
                        })
                    });
                    asn1EncodableVector3.Add(new Asn1Encodable[]
                    {
                        new SafeBag(PkcsObjectIdentifiers.CertBag, certBag2.ToAsn1Object(), new DerSet(asn1EncodableVector5))
                    });
                    set.Add(x509CertificateEntry.Certificate);
                }
            }
            foreach (Pkcs12Store.CertId key in this.chainCerts.Keys)
            {
                X509CertificateEntry x509CertificateEntry2 = (X509CertificateEntry)this.chainCerts[key];
                if (!set.Contains(x509CertificateEntry2.Certificate))
                {
                    CertBag             certBag3             = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(x509CertificateEntry2.Certificate.GetEncoded()));
                    Asn1EncodableVector asn1EncodableVector6 = new Asn1EncodableVector(new Asn1Encodable[0]);
                    foreach (string text7 in x509CertificateEntry2.BagAttributeKeys)
                    {
                        if (!text7.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                        {
                            asn1EncodableVector6.Add(new Asn1Encodable[]
                            {
                                new DerSequence(new Asn1Encodable[]
                                {
                                    new DerObjectIdentifier(text7),
                                    new DerSet(x509CertificateEntry2[text7])
                                })
                            });
                        }
                    }
                    asn1EncodableVector3.Add(new Asn1Encodable[]
                    {
                        new SafeBag(PkcsObjectIdentifiers.CertBag, certBag3.ToAsn1Object(), new DerSet(asn1EncodableVector6))
                    });
                }
            }
            byte[]      derEncoded2 = new DerSequence(asn1EncodableVector3).GetDerEncoded();
            ContentInfo contentInfo2;

            if (password == null)
            {
                contentInfo2 = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(derEncoded2));
            }
            else
            {
                byte[]        str           = Pkcs12Store.CryptPbeData(true, algorithmIdentifier, password, false, derEncoded2);
                EncryptedData encryptedData = new EncryptedData(PkcsObjectIdentifiers.Data, algorithmIdentifier, new BerOctetString(str));
                contentInfo2 = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, encryptedData.ToAsn1Object());
            }
            ContentInfo[] info = new ContentInfo[]
            {
                contentInfo,
                contentInfo2
            };
            byte[]      encoded      = new AuthenticatedSafe(info).GetEncoded(this.useDerEncoding ? "DER" : "BER");
            ContentInfo contentInfo3 = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(encoded));
            MacData     macData      = null;

            if (password != null)
            {
                byte[] array3 = new byte[20];
                random.NextBytes(array3);
                byte[] digest               = Pkcs12Store.CalculatePbeMac(OiwObjectIdentifiers.IdSha1, array3, 1024, password, false, encoded);
                AlgorithmIdentifier algID   = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);
                DigestInfo          digInfo = new DigestInfo(algID, digest);
                macData = new MacData(digInfo, array3, 1024);
            }
            Pfx             obj6 = new Pfx(contentInfo3, macData);
            DerOutputStream derOutputStream;

            if (this.useDerEncoding)
            {
                derOutputStream = new DerOutputStream(stream);
            }
            else
            {
                derOutputStream = new BerOutputStream(stream);
            }
            derOutputStream.WriteObject(obj6);
        }
Beispiel #5
0
        public void Load(Stream input, char[] password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            Asn1Sequence seq             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          pfx             = new Pfx(seq);
            ContentInfo  authSafe        = pfx.AuthSafe;
            bool         wrongPkcs12Zero = false;

            if (password != null && pfx.MacData != null)
            {
                MacData             macData     = pfx.MacData;
                DigestInfo          mac         = macData.Mac;
                AlgorithmIdentifier algorithmID = mac.AlgorithmID;
                byte[] salt     = macData.GetSalt();
                int    intValue = macData.IterationCount.IntValue;
                byte[] octets   = ((Asn1OctetString)authSafe.Content).GetOctets();
                byte[] a        = Pkcs12Store.CalculatePbeMac(algorithmID.ObjectID, salt, intValue, password, false, octets);
                byte[] digest   = mac.GetDigest();
                if (!Arrays.ConstantTimeAreEqual(a, digest))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }
                    a = Pkcs12Store.CalculatePbeMac(algorithmID.ObjectID, salt, intValue, password, true, octets);
                    if (!Arrays.ConstantTimeAreEqual(a, digest))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }
                    wrongPkcs12Zero = true;
                }
            }
            this.keys.Clear();
            this.localIds.Clear();
            this.unmarkedKeyEntry = null;
            IList list = Platform.CreateArrayList();

            if (authSafe.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octets2           = ((Asn1OctetString)authSafe.Content).GetOctets();
                AuthenticatedSafe authenticatedSafe = new AuthenticatedSafe((Asn1Sequence)Asn1Object.FromByteArray(octets2));
                ContentInfo[]     contentInfo       = authenticatedSafe.GetContentInfo();
                ContentInfo[]     array             = contentInfo;
                for (int i = 0; i < array.Length; i++)
                {
                    ContentInfo         contentInfo2 = array[i];
                    DerObjectIdentifier contentType  = contentInfo2.ContentType;
                    byte[] array2 = null;
                    if (contentType.Equals(PkcsObjectIdentifiers.Data))
                    {
                        array2 = ((Asn1OctetString)contentInfo2.Content).GetOctets();
                    }
                    else if (contentType.Equals(PkcsObjectIdentifiers.EncryptedData) && password != null)
                    {
                        EncryptedData instance = EncryptedData.GetInstance(contentInfo2.Content);
                        array2 = Pkcs12Store.CryptPbeData(false, instance.EncryptionAlgorithm, password, wrongPkcs12Zero, instance.Content.GetOctets());
                    }
                    if (array2 != null)
                    {
                        Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(array2);
                        foreach (Asn1Sequence seq2 in asn1Sequence)
                        {
                            SafeBag safeBag = new SafeBag(seq2);
                            if (safeBag.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                list.Add(safeBag);
                            }
                            else if (safeBag.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                this.LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(safeBag.BagValue), safeBag.BagAttributes, password, wrongPkcs12Zero);
                            }
                            else if (safeBag.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                this.LoadKeyBag(PrivateKeyInfo.GetInstance(safeBag.BagValue), safeBag.BagAttributes);
                            }
                        }
                    }
                }
            }
            this.certs.Clear();
            this.chainCerts.Clear();
            this.keyCerts.Clear();
            foreach (SafeBag safeBag2 in list)
            {
                CertBag         certBag         = new CertBag((Asn1Sequence)safeBag2.BagValue);
                byte[]          octets3         = ((Asn1OctetString)certBag.CertValue).GetOctets();
                X509Certificate x509Certificate = new X509CertificateParser().ReadCertificate(octets3);
                IDictionary     dictionary      = Platform.CreateHashtable();
                Asn1OctetString asn1OctetString = null;
                string          text            = null;
                if (safeBag2.BagAttributes != null)
                {
                    foreach (Asn1Sequence asn1Sequence2 in safeBag2.BagAttributes)
                    {
                        DerObjectIdentifier instance2 = DerObjectIdentifier.GetInstance(asn1Sequence2[0]);
                        Asn1Set             instance3 = Asn1Set.GetInstance(asn1Sequence2[1]);
                        if (instance3.Count > 0)
                        {
                            Asn1Encodable asn1Encodable = instance3[0];
                            if (dictionary.Contains(instance2.Id))
                            {
                                if (!dictionary[instance2.Id].Equals(asn1Encodable))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                dictionary.Add(instance2.Id, asn1Encodable);
                            }
                            if (instance2.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                text = ((DerBmpString)asn1Encodable).GetString();
                            }
                            else if (instance2.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                asn1OctetString = (Asn1OctetString)asn1Encodable;
                            }
                        }
                    }
                }
                Pkcs12Store.CertId   certId = new Pkcs12Store.CertId(x509Certificate.GetPublicKey());
                X509CertificateEntry value  = new X509CertificateEntry(x509Certificate, dictionary);
                this.chainCerts[certId] = value;
                if (this.unmarkedKeyEntry != null)
                {
                    if (this.keyCerts.Count == 0)
                    {
                        string text2 = Hex.ToHexString(certId.Id);
                        this.keyCerts[text2] = value;
                        this.keys[text2]     = this.unmarkedKeyEntry;
                    }
                }
                else
                {
                    if (asn1OctetString != null)
                    {
                        string key = Hex.ToHexString(asn1OctetString.GetOctets());
                        this.keyCerts[key] = value;
                    }
                    if (text != null)
                    {
                        this.certs[text] = value;
                    }
                }
            }
        }