Exemplo n.º 1
0
        public void EmptyPfx_BadPassword()
        {
            Pkcs12Builder builder = new Pkcs12Builder();

            builder.SealWithMac("correct password", s_digestAlgorithm, MacCount);
            ReadWrongPassword(builder.Encode(), "wrong password");
            ReadWrongPassword(builder.Encode(), string.Empty);
            ReadWrongPassword(builder.Encode(), null);
        }
Exemplo n.º 2
0
        public void EmptyPfx_NoMac()
        {
            Pkcs12Builder builder = new Pkcs12Builder();

            builder.SealWithoutIntegrity();
            ReadEmptyPfx(builder.Encode(), correctPassword: null);
        }
Exemplo n.º 3
0
        public void CertTwice_KeyOnce(bool addLocalKeyId)
        {
            string pw = nameof(CertTwice_KeyOnce);

            using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, s_exportableImportFlags))
                using (RSA key = cert.GetRSAPrivateKey())
                {
                    Pkcs12Builder      builder      = new Pkcs12Builder();
                    Pkcs12SafeContents keyContents  = new Pkcs12SafeContents();
                    Pkcs12SafeContents certContents = new Pkcs12SafeContents();

                    Pkcs12SafeBag keyBag   = keyContents.AddShroudedKey(key, pw, s_windowsPbe);
                    Pkcs12SafeBag certBag  = certContents.AddCertificate(cert);
                    Pkcs12SafeBag certBag2 = certContents.AddCertificate(cert);

                    if (addLocalKeyId)
                    {
                        certBag.Attributes.Add(s_keyIdOne);
                        certBag2.Attributes.Add(s_keyIdOne);
                        keyBag.Attributes.Add(s_keyIdOne);
                    }

                    AddContents(keyContents, builder, pw, encrypt: false);
                    AddContents(certContents, builder, pw, encrypt: true);
                    builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
                    byte[] pfxBytes = builder.Encode();

                    ReadUnreadablePfx(
                        pfxBytes,
                        pw,
                        // NTE_BAD_DATA
                        -2146893819);
                }
        }
Exemplo n.º 4
0
        public void SameCertTwice_NoKeys(bool addLocalKeyId)
        {
            string pw = nameof(SameCertTwice_NoKeys);

            using (var cert = new X509Certificate2(TestData.MsCertificate))
            {
                Pkcs12Builder      builder      = new Pkcs12Builder();
                Pkcs12SafeContents certContents = new Pkcs12SafeContents();

                Pkcs12SafeBag certBag  = certContents.AddCertificate(cert);
                Pkcs12SafeBag certBag2 = certContents.AddCertificate(cert);

                if (addLocalKeyId)
                {
                    certBag.Attributes.Add(s_keyIdOne);
                    certBag2.Attributes.Add(s_keyIdOne);
                }

                AddContents(certContents, builder, pw, encrypt: true);
                builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
                byte[] pfxBytes = builder.Encode();

                ReadMultiPfx(
                    pfxBytes,
                    pw,
                    cert,
                    new[] { cert, cert });
            }
        }
Exemplo n.º 5
0
        public void TwoCerts_CrossedKeys()
        {
            string pw = nameof(SameCertTwice_NoKeys);

            using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, s_exportableImportFlags))
                using (var cert2 = new X509Certificate2(TestData.MsCertificate))
                    using (RSA key = cert.GetRSAPrivateKey())
                    {
                        Pkcs12Builder      builder      = new Pkcs12Builder();
                        Pkcs12SafeContents keyContents  = new Pkcs12SafeContents();
                        Pkcs12SafeContents certContents = new Pkcs12SafeContents();

                        Pkcs12SafeBag keyBag   = keyContents.AddShroudedKey(key, pw, s_windowsPbe);
                        Pkcs12SafeBag certBag  = certContents.AddCertificate(cert);
                        Pkcs12SafeBag certBag2 = certContents.AddCertificate(cert2);

                        keyBag.Attributes.Add(s_keyIdOne);
                        certBag2.Attributes.Add(s_keyIdOne);

                        AddContents(keyContents, builder, pw, encrypt: false);
                        AddContents(certContents, builder, pw, encrypt: true);
                        builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
                        byte[] pfxBytes = builder.Encode();

                        // Windows seems to be applying both the implicit match and the LocalKeyId match,
                        // so it detects two hits against the same key and fails.
                        ReadUnreadablePfx(
                            pfxBytes,
                            pw,
                            // NTE_BAD_DATA
                            -2146893819);
                    }
        }
Exemplo n.º 6
0
        public void OneCert_TwentyKeys_NoMatches()
        {
            string pw = nameof(OneCert_NoKey_WithLocalKeyId);

            using (var cert = new X509Certificate2(TestData.MsCertificate))
                using (RSA rsa = RSA.Create(TestData.RsaBigExponentParams))
                {
                    Pkcs12Builder      builder      = new Pkcs12Builder();
                    Pkcs12SafeContents certContents = new Pkcs12SafeContents();
                    Pkcs12SafeContents keyContents  = new Pkcs12SafeContents();

                    Pkcs12CertBag certBag = certContents.AddCertificate(cert);
                    certBag.Attributes.Add(s_keyIdOne);

                    byte[] keyExport = rsa.ExportEncryptedPkcs8PrivateKey(pw, s_windowsPbe);

                    for (int i = 0; i < 20; i++)
                    {
                        Pkcs12SafeBag keyBag = new Pkcs12ShroudedKeyBag(keyExport, skipCopy: true);
                        keyContents.AddSafeBag(keyBag);

                        // Even with i=1 this won't match, because { 0x01 } != { 0x01, 0x00, 0x00, 0x00 } and
                        // { 0x01 } != { 0x00, 0x00, 0x00, 0x01 } (binary comparison, not "equivalence" comparison).
                        keyBag.Attributes.Add(new Pkcs9LocalKeyId(BitConverter.GetBytes(i)));
                    }

                    AddContents(keyContents, builder, pw, encrypt: false);
                    AddContents(certContents, builder, pw, encrypt: true);
                    builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
                    byte[] pfxBytes = builder.Encode();

                    ReadPfx(pfxBytes, pw, cert);
                }
        }
Exemplo n.º 7
0
        public static void CopyEncryptedSafeContents(bool withSpan)
        {
            Pkcs12Builder builder1 = new Pkcs12Builder();
            Pkcs12Builder builder2 = new Pkcs12Builder();

            Pkcs12SafeContents contents = new Pkcs12SafeContents();

            contents.AddSecret(s_zeroOid, s_derNull);

            if (withSpan)
            {
                builder1.AddSafeContentsEncrypted(contents, ReadOnlySpan <byte> .Empty, s_pbkdf2Parameters);
            }
            else
            {
                builder1.AddSafeContentsEncrypted(contents, (byte[])null, s_pbkdf2Parameters);
            }

            builder1.SealWithoutIntegrity();

            byte[]     encoded1 = builder1.Encode();
            Pkcs12Info info     = Pkcs12Info.Decode(encoded1, out _, skipCopy: true);

            Assert.Equal(Pkcs12IntegrityMode.None, info.IntegrityMode);
            Assert.Equal(1, info.AuthenticatedSafe.Count);

            builder2.AddSafeContentsUnencrypted(info.AuthenticatedSafe[0]);
            builder2.SealWithoutIntegrity();

            byte[] encoded2 = builder2.Encode();
            Assert.Equal(encoded1.ByteArrayToHex(), encoded2.ByteArrayToHex());
        }
Exemplo n.º 8
0
        public static void BuildWithoutContents(bool withMac)
        {
            string        password;
            Pkcs12Builder builder = new Pkcs12Builder();

            if (withMac)
            {
                password = "******";
                builder.SealWithMac(password, HashAlgorithmName.SHA1, 2);
            }
            else
            {
                password = null;
                builder.SealWithoutIntegrity();
            }

            byte[] encoded = builder.Encode();

            const string FullyEmptyHex =
                "3016020103301106092A864886F70D010701A00404023000";

            if (withMac)
            {
                Assert.Equal(60 + FullyEmptyHex.Length / 2, encoded.Length);
            }
            else
            {
                Assert.Equal(FullyEmptyHex, encoded.ByteArrayToHex());
            }

            X509Certificate2Collection collection = new X509Certificate2Collection();

            collection.Import(encoded, password, X509KeyStorageFlags.DefaultKeySet);
            Assert.Equal(0, collection.Count);
        }
Exemplo n.º 9
0
        public static void EncryptEncryptedSafeContents()
        {
            Pkcs12Builder builder1 = new Pkcs12Builder();
            Pkcs12Builder builder2 = new Pkcs12Builder();

            Pkcs12SafeContents contents = new Pkcs12SafeContents();

            contents.AddSecret(s_zeroOid, s_derNull);

            builder1.AddSafeContentsEncrypted(contents, ReadOnlySpan <byte> .Empty, s_pbkdf2Parameters);
            builder1.SealWithoutIntegrity();

            byte[]     encoded = builder1.Encode();
            Pkcs12Info info    = Pkcs12Info.Decode(encoded, out _, skipCopy: true);

            Assert.Equal(Pkcs12IntegrityMode.None, info.IntegrityMode);
            Assert.Equal(1, info.AuthenticatedSafe.Count);

            AssertExtensions.Throws <ArgumentException>(
                "safeContents",
                () => builder2.AddSafeContentsEncrypted(
                    info.AuthenticatedSafe[0],
                    "nope",
                    s_pbkdf2Parameters));

            AssertExtensions.Throws <ArgumentException>(
                "safeContents",
                () => builder2.AddSafeContentsEncrypted(
                    info.AuthenticatedSafe[0],
                    s_derNull.Span,
                    s_pbkdf2Parameters));
        }
Exemplo n.º 10
0
        public static void BuildWithEmptySafeContents(bool encrypted)
        {
            string pw = nameof(BuildWithEmptySafeContents);

            Pkcs12Builder      builder = new Pkcs12Builder();
            Pkcs12SafeContents empty   = new Pkcs12SafeContents();

            if (encrypted)
            {
                builder.AddSafeContentsEncrypted(empty, pw, s_win7Pbe);
            }
            else
            {
                builder.AddSafeContentsUnencrypted(empty);
            }

            builder.SealWithMac(pw, HashAlgorithmName.SHA1, 1);
            byte[] pfxBytes = builder.Encode();

            X509Certificate2Collection coll = new X509Certificate2Collection();

            coll.Import(pfxBytes, pw, default);

            Assert.Equal(0, coll.Count);
        }
Exemplo n.º 11
0
        public static void WriteOneCertNoKeys_Encrypted()
        {
            Pkcs12SafeContents contents = new Pkcs12SafeContents();

            byte[] rawData;

            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate())
            {
                contents.AddCertificate(cert);
                rawData = cert.RawData;
            }

            const string password = nameof(WriteOneCertNoKeys_NoEncryption);

            Pkcs12Builder builder = new Pkcs12Builder();

            builder.AddSafeContentsEncrypted(
                contents,
                password,
                s_win7Pbe);

            builder.SealWithMac(password, HashAlgorithmName.SHA1, 1024);
            byte[] pfx = builder.Encode();

            ImportedCollection coll =
                ImportedCollection.Import(pfx, password, X509KeyStorageFlags.EphemeralKeySet);

            using (coll)
            {
                Assert.Equal(1, coll.Collection.Count);
                Assert.Equal(rawData, coll.Collection[0].RawData);
                Assert.False(coll.Collection[0].HasPrivateKey, "coll.Collection[0].HasPrivateKey");
            }
        }
Exemplo n.º 12
0
        public static X509Certificate2 CreateCertificateWithPrivateKey(
            X509Certificate2 certificate,
            AsymmetricAlgorithm privateKey,
            string password = null)
        {
            var builder  = new Pkcs12Builder();
            var contents = new Pkcs12SafeContents();

            contents.AddCertificate(certificate);
            contents.AddKeyUnencrypted(privateKey);
            builder.AddSafeContentsUnencrypted(contents);

            // OpenSSL requires the file to have a mac, without mac this will run on Windows but not on Linux
            builder.SealWithMac(password, HashAlgorithmName.SHA256, 1);
            var pkcs12bytes = builder.Encode();

            if (string.IsNullOrEmpty(password))
            {
                var certificateOut = new X509Certificate2(pkcs12bytes);
                return(certificateOut);
            }
            else
            {
                var certificateOut = new X509Certificate2(pkcs12bytes, password);
                return(certificateOut);
            }
        }
Exemplo n.º 13
0
        public static void ReadSerializedData(bool encryptSafe)
        {
            Pkcs12SafeContents container = new Pkcs12SafeContents();

            Pkcs12SafeContents builtContents = new Pkcs12SafeContents();

            builtContents.AddSecret(s_zeroOid, s_derNull);

            builtContents.AddSecret(s_zeroOid, new byte[] { 4, 1, 2 }).Attributes.Add(
                new Pkcs9LocalKeyId(s_derNull.Span));

            builtContents.AddSecret(s_zeroOid, new byte[] { 4, 1, 3 });
            container.AddNestedContents(builtContents);

            Pkcs12Builder builder = new Pkcs12Builder();

            if (encryptSafe)
            {
                builder.AddSafeContentsEncrypted(container, s_derNull.Span, s_pbkdf2Parameters);
            }
            else
            {
                builder.AddSafeContentsUnencrypted(container);
            }

            builder.SealWithoutIntegrity();
            byte[] encoded = builder.Encode();

            Pkcs12Info         info     = Pkcs12Info.Decode(encoded, out _, skipCopy: true);
            Pkcs12SafeContents onlySafe = info.AuthenticatedSafe.Single();

            if (encryptSafe)
            {
                onlySafe.Decrypt(s_derNull.Span);
            }

            Pkcs12SafeBag         onlyBag         = onlySafe.GetBags().Single();
            Pkcs12SafeContentsBag safeContentsBag = Assert.IsType <Pkcs12SafeContentsBag>(onlyBag);
            Pkcs12SafeContents    readContents    = safeContentsBag.SafeContents;

            Assert.Equal(
                Pkcs12ConfidentialityMode.None,
                readContents.ConfidentialityMode);

            Assert.True(readContents.IsReadOnly);

            List <Pkcs12SafeBag> bags1 = builtContents.GetBags().ToList();
            List <Pkcs12SafeBag> bags2 = readContents.GetBags().ToList();

            Assert.Equal(bags1.Count, bags2.Count);

            for (int i = 0; i < bags2.Count; i++)
            {
                byte[] encoded1 = bags1[i].Encode();
                byte[] encoded2 = bags1[i].Encode();

                Assert.True(encoded1.AsSpan().SequenceEqual(encoded2), $"Bag {i} encodes the same");
            }
        }
Exemplo n.º 14
0
        public static void EncodeUnsealed()
        {
            Pkcs12Builder builder = new Pkcs12Builder();

            Assert.False(builder.IsSealed);
            Assert.Throws <InvalidOperationException>(() => builder.Encode());
            Assert.Throws <InvalidOperationException>(() => builder.TryEncode(Span <byte> .Empty, out _));
        }
Exemplo n.º 15
0
        public void OneCert_ExtraKeyBadEncoding(bool badTag)
        {
            string pw = nameof(OneCert_ExtraKeyBadEncoding);

            using (var cert = new X509Certificate2(TestData.MsCertificate))
            {
                Pkcs12Builder      builder      = new Pkcs12Builder();
                Pkcs12SafeContents certContents = new Pkcs12SafeContents();
                Pkcs12SafeContents keyContents  = new Pkcs12SafeContents();

                // SEQUENCE { INTEGER(1) } is not a valid RSAPrivateKey, it should be
                // SEQUENCE { INTEGER(N), INTEGER(E), ... (D, P, Q, DP, DQ, QInv) }
                // So the conclusion is "unexpected end of data"
                byte[] badKeyBytes = { 0x30, 0x03, 0x02, 0x01, 0x01 };

                // In "badTag" we make the INTEGER be OCTET STRING, triggering a different
                // "uh, I can't read this..." error.
                if (badTag)
                {
                    badKeyBytes[2] = 0x04;
                }

                Pkcs8PrivateKeyInfo pk8 = new Pkcs8PrivateKeyInfo(
                    // The correct RSA OID.
                    new Oid("1.2.840.113549.1.1.1", null),
                    null,
                    badKeyBytes,
                    skipCopies: true);

                // Note that neither the cert nor the key have a LocalKeyId attribute.
                // The existence of this unreadable key is enough to abort the load on older Windows
                keyContents.AddSafeBag(new Pkcs12ShroudedKeyBag(pk8.Encrypt(pw, s_windowsPbe)));
                certContents.AddCertificate(cert);

                AddContents(keyContents, builder, pw, encrypt: false);
                AddContents(certContents, builder, pw, encrypt: true);

                builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
                byte[] pfxBytes = builder.Encode();

                if (s_loaderFailsKeysEarly)
                {
                    // CRYPT_E_ASN1_BADTAG or CRYPT_E_ASN1_EOD
                    int expectedWin32Error = badTag ? -2146881269 : -2146881278;

                    ReadUnreadablePfx(
                        pfxBytes,
                        pw,
                        expectedWin32Error);
                }
                else
                {
                    ReadPfx(pfxBytes, pw, cert);
                }
            }
        }
Exemplo n.º 16
0
        public void EmptyPfx_NoMac_ArbitraryPassword()
        {
            Pkcs12Builder builder = new Pkcs12Builder();

            builder.SealWithoutIntegrity();
            byte[] pfxBytes = builder.Encode();

            ReadEmptyPfx(pfxBytes, "arbitrary password");
            ReadEmptyPfx(pfxBytes, "other arbitrary password");
        }
Exemplo n.º 17
0
        public void EmptyPfx_EmptyPassword()
        {
            Pkcs12Builder builder = new Pkcs12Builder();

            builder.SealWithMac(string.Empty, s_digestAlgorithm, MacCount);
            byte[] pfxBytes = builder.Encode();

            ReadEmptyPfx(pfxBytes, correctPassword: null);
            ReadEmptyPfx(pfxBytes, correctPassword: string.Empty);
        }
Exemplo n.º 18
0
        public static void WriteOneCertWithKey_LikeWindows()
        {
            Pkcs12SafeContents safe1 = new Pkcs12SafeContents();
            Pkcs12SafeContents safe2 = new Pkcs12SafeContents();

            byte[] rawData;

            Pkcs9LocalKeyId localKeyId = new Pkcs9LocalKeyId(new byte[] { 1 });
            const string    password   = nameof(WriteOneCertWithKey_LikeWindows);

            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey(true))
            {
                Pkcs12CertBag certBag = safe1.AddCertificate(cert);
                certBag.Attributes.Add(localKeyId);

                rawData = cert.RawData;

                Pkcs12ShroudedKeyBag keyBag;

                using (RSA rsa = cert.GetRSAPrivateKey())
                {
                    keyBag = safe2.AddShroudedKey(
                        rsa,
                        password,
                        s_win7Pbe);
                }

                keyBag.Attributes.Add(localKeyId);
            }

            Pkcs12Builder builder = new Pkcs12Builder();

            builder.AddSafeContentsEncrypted(
                safe1,
                password,
                s_win7Pbe);

            builder.AddSafeContentsUnencrypted(safe2);

            builder.SealWithMac(password, HashAlgorithmName.SHA1, 2068);
            byte[] pfx = builder.Encode();

            ImportedCollection coll =
                ImportedCollection.Import(pfx, password, X509KeyStorageFlags.EphemeralKeySet);

            using (coll)
            {
                Assert.Equal(1, coll.Collection.Count);
                Assert.Equal(rawData, coll.Collection[0].RawData);
                Assert.True(coll.Collection[0].HasPrivateKey, "coll.Collection[0].HasPrivateKey");
            }
        }
Exemplo n.º 19
0
        public static void MacOmitsImplicit1()
        {
            Pkcs12Builder builder1 = new Pkcs12Builder();
            Pkcs12Builder builder2 = new Pkcs12Builder();

            builder1.SealWithMac("hi", HashAlgorithmName.SHA1, 1);
            builder2.SealWithMac("hi", HashAlgorithmName.SHA1, 2);

            byte[] encode1 = builder1.Encode();
            byte[] encode2 = builder2.Encode();

            Assert.Equal(3 + encode1.Length, encode2.Length);
        }
Exemplo n.º 20
0
        public void CertAndKeyTwice(bool addLocalKeyId, bool crossIdentifiers)
        {
            string pw = nameof(CertAndKeyTwice);

            using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, s_exportableImportFlags))
                using (RSA key = cert.GetRSAPrivateKey())
                {
                    Pkcs12Builder      builder      = new Pkcs12Builder();
                    Pkcs12SafeContents keyContents  = new Pkcs12SafeContents();
                    Pkcs12SafeContents certContents = new Pkcs12SafeContents();

                    Pkcs12SafeBag key1  = keyContents.AddShroudedKey(key, pw, s_windowsPbe);
                    Pkcs12SafeBag key2  = keyContents.AddShroudedKey(key, pw, s_windowsPbe);
                    Pkcs12SafeBag cert1 = certContents.AddCertificate(cert);
                    Pkcs12SafeBag cert2 = certContents.AddCertificate(cert);

                    if (addLocalKeyId)
                    {
                        (crossIdentifiers ? key2 : key1).Attributes.Add(s_keyIdOne);
                        cert1.Attributes.Add(s_keyIdOne);

                        Pkcs9LocalKeyId id2 = new Pkcs9LocalKeyId(cert.GetCertHash());
                        (crossIdentifiers ? key1 : key2).Attributes.Add(id2);
                        cert2.Attributes.Add(id2);
                    }

                    AddContents(keyContents, builder, pw, encrypt: false);
                    AddContents(certContents, builder, pw, encrypt: true);
                    builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
                    byte[] pfxBytes = builder.Encode();

                    if (addLocalKeyId)
                    {
                        ReadMultiPfx(
                            pfxBytes,
                            pw,
                            cert,
                            new[] { cert, cert },
                            CheckKeyConsistency);
                    }
                    else
                    {
                        ReadUnreadablePfx(
                            pfxBytes,
                            pw,
                            // NTE_BAD_DATA
                            -2146893819);
                    }
                }
        }
Exemplo n.º 21
0
        public void OneCert_NoKeys_EncryptedEmptyPassword_NoMac()
        {
            using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate))
            {
                Pkcs12Builder      builder      = new Pkcs12Builder();
                Pkcs12SafeContents certContents = new Pkcs12SafeContents();
                certContents.AddCertificate(cert);
                builder.AddSafeContentsEncrypted(certContents, string.Empty, s_windowsPbe);
                builder.SealWithoutIntegrity();
                byte[] pfxBytes = builder.Encode();

                ReadPfx(pfxBytes, null, cert);
                ReadPfx(pfxBytes, string.Empty, cert);
            }
        }
Exemplo n.º 22
0
        public void Setup()
        {
            _certPath = $"{PathName}/leaf.p12";

            using var wrongKey = RSA.Create();
            var builder      = new Pkcs12Builder();
            var safeContents = new Pkcs12SafeContents();
            var pbeParams    = new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 2048);          // openssl defaults

            safeContents.AddCertificate(_leaf);
            safeContents.AddShroudedKey(wrongKey, Password, pbeParams);
            builder.AddSafeContentsEncrypted(safeContents, Password, pbeParams);
            builder.SealWithMac(Password, HashAlgorithmName.SHA1, 2048);             //openssl defaults

            File.WriteAllBytes(_certPath, builder.Encode());
        }
Exemplo n.º 23
0
        public void Setup()
        {
            _certPath = $"{PathName}/bundle.p12";

            using var rsa = RSA.Create();
            rsa.ImportRSAPrivateKey(_leaf.GetRSAPrivateKey() !.ExportRSAPrivateKey(), out _);
            var builder      = new Pkcs12Builder();
            var safeContents = new Pkcs12SafeContents();
            var pbeParams    = new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 2048);          // openssl defaults

            safeContents.AddShroudedKey(rsa, Password, pbeParams);
            builder.AddSafeContentsEncrypted(safeContents, Password, pbeParams);
            builder.SealWithMac(Password, HashAlgorithmName.SHA1, 2048);             //openssl defaults

            File.WriteAllBytes(_certPath, builder.Encode());
        }
Exemplo n.º 24
0
        private static X509Certificate2 CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey)
        {
            var builder  = new Pkcs12Builder();
            var contents = new Pkcs12SafeContents();

            contents.AddCertificate(certificate);
            contents.AddKeyUnencrypted(privateKey);
            builder.AddSafeContentsUnencrypted(contents);

            // OpenSSL requires the file to have a mac, without mac this will run on Windows but not on Linux
            builder.SealWithMac("temp", HashAlgorithmName.SHA256, 1);
            var pkcs12bytes = builder.Encode();

            var certificateWithKey = new X509Certificate2(pkcs12bytes, "temp");

            return(certificateWithKey);
        }
Exemplo n.º 25
0
        public void OneCorruptCert()
        {
            string             pw       = nameof(OneCorruptCert);
            Pkcs12Builder      builder  = new Pkcs12Builder();
            Pkcs12SafeContents contents = new Pkcs12SafeContents();

            contents.AddSafeBag(new Pkcs12CertBag(new Oid("1.2.840.113549.1.9.22.1"), new byte[] { 0x05, 0x00 }));
            AddContents(contents, builder, pw, encrypt: true);
            builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
            byte[] pfxBytes = builder.Encode();

            ReadUnreadablePfx(
                pfxBytes,
                pw,
                // CRYPT_E_BAD_ENCODE
                -2146885630);
        }
Exemplo n.º 26
0
        public static void WriteEmpty(int iterationCount)
        {
            Pkcs12Builder builder  = new Pkcs12Builder();
            string        password = $"Password{iterationCount}IsMyVoice";

            // Windows 7 through 10-1709 only support SHA-1 as the MAC PRF
            builder.SealWithMac(password, HashAlgorithmName.SHA1, iterationCount);

            byte[] emptyPfx = builder.Encode();

            ImportedCollection coll =
                ImportedCollection.Import(emptyPfx, password, X509KeyStorageFlags.EphemeralKeySet);

            using (coll)
            {
                Assert.Equal(0, coll.Collection.Count);
            }
        }
Exemplo n.º 27
0
        public void OneCert_MismatchedKey()
        {
            string pw = nameof(OneCert_MismatchedKey);

            // Build the PFX in the normal Windows style, except the private key doesn't match.
            using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, s_exportableImportFlags))
                using (RSA realKey = cert.GetRSAPrivateKey())
                    using (RSA key = RSA.Create(realKey.KeySize))
                    {
                        Pkcs12Builder      builder      = new Pkcs12Builder();
                        Pkcs12SafeContents keyContents  = new Pkcs12SafeContents();
                        Pkcs12SafeBag      keyBag       = keyContents.AddShroudedKey(key, pw, s_windowsPbe);
                        Pkcs12SafeContents certContents = new Pkcs12SafeContents();
                        Pkcs12SafeBag      certBag      = certContents.AddCertificate(cert);

                        keyBag.Attributes.Add(s_keyIdOne);
                        certBag.Attributes.Add(s_keyIdOne);

                        builder.AddSafeContentsUnencrypted(keyContents);
                        builder.AddSafeContentsEncrypted(certContents, pw, s_windowsPbe);
                        builder.SealWithoutIntegrity();
                        byte[] pfxBytes = builder.Encode();

                        // On macOS the cert will come back with HasPrivateKey being false.
                        if (OperatingSystem.IsMacOS())
                        {
                            using (var publicCert = new X509Certificate2(cert.RawData))
                            {
                                ReadPfx(
                                    pfxBytes,
                                    pw,
                                    publicCert);
                            }

                            return;
                        }

                        ReadPfx(
                            pfxBytes,
                            pw,
                            cert,
                            CheckKeyConsistencyFails);
                    }
        }
Exemplo n.º 28
0
        public static void WriteOneCertWithKey_Encrypted_SameSafe()
        {
            Pkcs12SafeContents contents = new Pkcs12SafeContents();

            byte[] rawData;

            Pkcs9LocalKeyId localKeyId = new Pkcs9LocalKeyId(new byte[] { 1 });

            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey(true))
                using (RSA certKey = cert.GetRSAPrivateKey())
                    using (RSA exportableKey = certKey.MakeExportable())
                    {
                        Pkcs12CertBag certBag = contents.AddCertificate(cert);
                        certBag.Attributes.Add(localKeyId);

                        rawData = cert.RawData;

                        Pkcs12KeyBag keyBag = contents.AddKeyUnencrypted(exportableKey);
                        keyBag.Attributes.Add(localKeyId);
                    }

            const string password = nameof(WriteOneCertWithKey_Encrypted_SameSafe);

            Pkcs12Builder builder = new Pkcs12Builder();

            builder.AddSafeContentsEncrypted(
                contents,
                password,
                s_win7Pbe);

            builder.SealWithMac(password, HashAlgorithmName.SHA1, 1024);
            byte[] pfx = builder.Encode();

            ImportedCollection coll =
                ImportedCollection.Import(pfx, password, X509KeyStorageFlags.EphemeralKeySet);

            using (coll)
            {
                Assert.Equal(1, coll.Collection.Count);
                Assert.Equal(rawData, coll.Collection[0].RawData);
                Assert.True(coll.Collection[0].HasPrivateKey, "coll.Collection[0].HasPrivateKey");
            }
        }
Exemplo n.º 29
0
        public void OneCert_NoKey_WithLocalKeyId()
        {
            string pw = nameof(OneCert_NoKey_WithLocalKeyId);

            using (var cert = new X509Certificate2(TestData.MsCertificate))
            {
                Pkcs12Builder      builder      = new Pkcs12Builder();
                Pkcs12SafeContents certContents = new Pkcs12SafeContents();

                Pkcs12CertBag certBag = certContents.AddCertificate(cert);
                certBag.Attributes.Add(s_keyIdOne);

                AddContents(certContents, builder, pw, encrypt: true);
                builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
                byte[] pfxBytes = builder.Encode();

                ReadPfx(pfxBytes, pw, cert);
            }
        }
Exemplo n.º 30
0
        public void TwoCerts_OneKey(bool certWithKeyFirst)
        {
            string pw = nameof(TwoCerts_OneKey);

            // Build the PFX in the normal Windows style, except the private key doesn't match.
            using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, s_exportableImportFlags))
                using (var cert2 = new X509Certificate2(TestData.MsCertificate))
                    using (RSA key = cert.GetRSAPrivateKey())
                    {
                        Pkcs12Builder      builder      = new Pkcs12Builder();
                        Pkcs12SafeContents certContents = new Pkcs12SafeContents();
                        Pkcs12SafeContents keyContents  = new Pkcs12SafeContents();

                        Pkcs12SafeBag      certBag;
                        Pkcs12SafeBag      keyBag = keyContents.AddShroudedKey(key, pw, s_windowsPbe);
                        X509Certificate2[] expectedOrder;

                        if (certWithKeyFirst)
                        {
                            certBag = certContents.AddCertificate(cert);
                            certContents.AddCertificate(cert2);

                            expectedOrder = new[] { cert2, cert };
                        }
                        else
                        {
                            certContents.AddCertificate(cert2);
                            certBag = certContents.AddCertificate(cert);

                            expectedOrder = new[] { cert, cert2 };
                        }

                        certBag.Attributes.Add(s_keyIdOne);
                        keyBag.Attributes.Add(s_keyIdOne);

                        AddContents(keyContents, builder, pw, encrypt: false);
                        AddContents(certContents, builder, pw, encrypt: true);

                        builder.SealWithMac(pw, s_digestAlgorithm, MacCount);
                        ReadMultiPfx(builder.Encode(), pw, cert, expectedOrder);
                    }
        }