예제 #1
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);
                }
        }
예제 #2
0
        public static void AddBagDisallowedInReadOnly()
        {
            Pkcs12SafeContents contents = MakeReadonly(new Pkcs12SafeContents());
            Pkcs12CertBag      certBag  = new Pkcs12CertBag(s_zeroOid, s_derNull);

            Assert.True(contents.IsReadOnly);
            Assert.Throws <InvalidOperationException>(() => contents.AddSafeBag(certBag));
        }
예제 #3
0
        public static void DataNotValidatedInCtor()
        {
            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate())
            {
                var certBag = new Pkcs12CertBag(s_x509TypeOid, cert.RawData);

                Assert.True(certBag.IsX509Certificate, "certBag.IsX509Certificate");
                Assert.ThrowsAny <CryptographicException>(() => certBag.GetCertificate());
            }
        }
예제 #4
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");
            }
        }
예제 #5
0
        public static void CertificateReadsSuccessfully()
        {
            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate())
            {
                Pkcs12SafeContents contents = new Pkcs12SafeContents();
                Pkcs12CertBag      certBag  = contents.AddCertificate(cert);

                using (X509Certificate2 extracted = certBag.GetCertificate())
                {
                    Assert.True(extracted.RawData.AsSpan().SequenceEqual(cert.RawData));
                }
            }
        }
예제 #6
0
        public static void VerifyIsX509(string oidValue, bool expectedValue)
        {
            var certBag = new Pkcs12CertBag(new Oid(oidValue), s_derNull);

            if (expectedValue)
            {
                Assert.True(certBag.IsX509Certificate, "certBag.IsX509Certificate");
                Assert.ThrowsAny <CryptographicException>(() => certBag.GetCertificate());
            }
            else
            {
                Assert.False(certBag.IsX509Certificate, "certBag.IsX509Certificate");
                Assert.Throws <InvalidOperationException>(() => certBag.GetCertificate());
            }
        }
예제 #7
0
        public static void OidCtorPreservesFriendlyName()
        {
            Oid oid        = new Oid(Oids.Pkcs7Data, "Hello");
            var certBag    = new Pkcs12CertBag(oid, s_derNull);
            Oid firstCall  = certBag.GetCertificateType();
            Oid secondCall = certBag.GetCertificateType();

            Assert.NotSame(oid, firstCall);
            Assert.NotSame(oid, secondCall);
            Assert.NotSame(firstCall, secondCall);
            Assert.Equal(oid.Value, firstCall.Value);
            Assert.Equal(oid.Value, secondCall.Value);
            Assert.Equal("Hello", firstCall.FriendlyName);
            Assert.Equal("Hello", secondCall.FriendlyName);
        }
예제 #8
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");
            }
        }
예제 #9
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);
            }
        }
예제 #10
0
        public static void ReadIndefiniteEncodingNoMac(int trailingByteCount)
        {
            ReadOnlyMemory <byte> source = PadContents(Pkcs12Documents.IndefiniteEncodingNoMac, trailingByteCount);

            Pkcs12Info info = Pkcs12Info.Decode(
                source,
                out int bytesRead,
                skipCopy: true);

            Assert.Equal(Pkcs12Documents.IndefiniteEncodingNoMac.Length, bytesRead);
            Assert.Equal(Pkcs12IntegrityMode.None, info.IntegrityMode);

            ReadOnlyCollection <Pkcs12SafeContents> safes = info.AuthenticatedSafe;

            Assert.Equal(2, safes.Count);

            Pkcs12SafeContents firstSafe  = safes[0];
            Pkcs12SafeContents secondSafe = safes[1];

            Assert.Equal(Pkcs12ConfidentialityMode.None, firstSafe.ConfidentialityMode);
            Assert.Equal(Pkcs12ConfidentialityMode.None, secondSafe.ConfidentialityMode);

            Assert.True(firstSafe.IsReadOnly, "firstSafe.IsReadOnly");
            Assert.True(secondSafe.IsReadOnly, "secondSafe.IsReadOnly");

            Pkcs12SafeBag[] firstContents  = firstSafe.GetBags().ToArray();
            Pkcs12SafeBag[] secondContents = secondSafe.GetBags().ToArray();

            Assert.Equal(1, firstContents.Length);
            Assert.Equal(1, secondContents.Length);

            Pkcs12KeyBag  keyBag  = Assert.IsType <Pkcs12KeyBag>(firstContents[0]);
            Pkcs12CertBag certBag = Assert.IsType <Pkcs12CertBag>(secondContents[0]);

            CryptographicAttributeObjectCollection keyBagAttrs  = keyBag.Attributes;
            CryptographicAttributeObjectCollection certBagAttrs = certBag.Attributes;

            Assert.Equal(2, keyBagAttrs.Count);
            Assert.Equal(2, certBagAttrs.Count);

            Assert.Equal(Oids.FriendlyName, keyBagAttrs[0].Oid.Value);
            Assert.Equal(1, keyBagAttrs[0].Values.Count);
            Assert.Equal(Oids.LocalKeyId, keyBagAttrs[1].Oid.Value);
            Assert.Equal(1, keyBagAttrs[1].Values.Count);

            Pkcs9AttributeObject keyFriendlyName =
                Assert.IsAssignableFrom <Pkcs9AttributeObject>(keyBagAttrs[0].Values[0]);

            Pkcs9LocalKeyId keyKeyId = Assert.IsType <Pkcs9LocalKeyId>(keyBagAttrs[1].Values[0]);

            Assert.Equal(Oids.FriendlyName, certBagAttrs[0].Oid.Value);
            Assert.Equal(1, certBagAttrs[0].Values.Count);
            Assert.Equal(Oids.LocalKeyId, certBagAttrs[1].Oid.Value);
            Assert.Equal(1, certBagAttrs[1].Values.Count);

            Pkcs9AttributeObject certFriendlyName =
                Assert.IsAssignableFrom <Pkcs9AttributeObject>(certBagAttrs[0].Values[0]);

            Pkcs9LocalKeyId certKeyId = Assert.IsType <Pkcs9LocalKeyId>(certBagAttrs[1].Values[0]);

            // This PFX gave a friendlyName value of "cert" to both the key and the cert.
            Assert.Equal("1E080063006500720074", keyFriendlyName.RawData.ByteArrayToHex());
            Assert.Equal(keyFriendlyName.RawData, certFriendlyName.RawData);

            // The private key (KeyBag) and the public key (CertBag) are matched from their keyId value.
            Assert.Equal("0414EDF3D122CF623CF0CFC9CD226261E8415A83E630", keyKeyId.RawData.ByteArrayToHex());
            Assert.Equal("EDF3D122CF623CF0CFC9CD226261E8415A83E630", keyKeyId.KeyId.ByteArrayToHex());
            Assert.Equal(keyKeyId.RawData, certKeyId.RawData);

            using (X509Certificate2 cert = certBag.GetCertificate())
                using (RSA privateKey = RSA.Create())
                    using (RSA publicKey = cert.GetRSAPublicKey())
                    {
                        privateKey.ImportPkcs8PrivateKey(keyBag.Pkcs8PrivateKey.Span, out _);

                        Assert.Equal(
                            publicKey.ExportSubjectPublicKeyInfo().ByteArrayToHex(),
                            privateKey.ExportSubjectPublicKeyInfo().ByteArrayToHex());
                    }
        }
예제 #11
0
        public static void Test1()
        {
            var loader = (CertLoaderFromRawData)Certificates.RSAKeyTransferCapi1;
            ReadOnlyMemory <byte> pfxData = loader.PfxData;

            Pkcs12Info info = Pkcs12Info.Decode(pfxData, out int bytesConsumed);

            Assert.Equal(pfxData.Length, bytesConsumed);

            Assert.Equal(Pkcs12IntegrityMode.Password, info.IntegrityMode);
            CheckMac(info, loader.Password);

            ReadOnlyCollection <Pkcs12SafeContents> authSafe = info.AuthenticatedSafe;

            Assert.Same(authSafe, info.AuthenticatedSafe);
            Assert.Equal(2, authSafe.Count);

            Assert.Equal(Pkcs12ConfidentialityMode.None, authSafe[0].ConfidentialityMode);
            Assert.Equal(Pkcs12ConfidentialityMode.None, authSafe[1].ConfidentialityMode);

            List <Pkcs12SafeBag> safe0Bags = new List <Pkcs12SafeBag>(authSafe[0].GetBags());

            Assert.Equal(1, safe0Bags.Count);
            Pkcs12ShroudedKeyBag shroudedKeyBag = Assert.IsType <Pkcs12ShroudedKeyBag>(safe0Bags[0]);

            CryptographicAttributeObjectCollection keyBagAttrs = shroudedKeyBag.Attributes;

            Assert.Same(keyBagAttrs, shroudedKeyBag.Attributes);
            Assert.Equal(2, keyBagAttrs.Count);
            Assert.Equal(Oids.LocalKeyId, keyBagAttrs[0].Oid.Value);
            Assert.Equal(1, keyBagAttrs[0].Values.Count);
            Pkcs9LocalKeyId keyKeyId = Assert.IsType <Pkcs9LocalKeyId>(keyBagAttrs[0].Values[0]);

            Assert.Equal("1.3.6.1.4.1.311.17.1", keyBagAttrs[1].Oid.Value);
            Assert.Equal(1, keyBagAttrs[1].Values.Count);
            Pkcs9AttributeObject cspNameAttr = Assert.IsType <Pkcs9AttributeObject>(keyBagAttrs[1].Values[0]);

            byte[] cspNameBytes = Encoding.BigEndianUnicode.GetBytes("Microsoft Strong Cryptographic Provider");

            Assert.Equal(
                $"1E{cspNameBytes.Length:X2}{cspNameBytes.ByteArrayToHex()}",
                cspNameAttr.RawData.ByteArrayToHex());

            List <Pkcs12SafeBag> safe1Bags = new List <Pkcs12SafeBag>(authSafe[1].GetBags());

            Assert.Equal(1, safe0Bags.Count);
            Assert.IsType <Pkcs12CertBag>(safe1Bags[0]);
            Pkcs12CertBag certBag = (Pkcs12CertBag)safe1Bags[0];

            Assert.True(certBag.IsX509Certificate, "certBag.IsX509Certificate");
            Assert.InRange(certBag.EncodedCertificate.Length, loader.CerData.Length + 2, int.MaxValue);

            CryptographicAttributeObjectCollection certBagAttrs = certBag.Attributes;

            Assert.Same(certBagAttrs, certBag.Attributes);
            Assert.Equal(1, certBagAttrs.Count);
            Assert.Equal(Oids.LocalKeyId, certBagAttrs[0].Oid.Value);
            Assert.Equal(1, certBagAttrs[0].Values.Count);
            Pkcs9LocalKeyId certKeyId = Assert.IsType <Pkcs9LocalKeyId>(certBagAttrs[0].Values[0]);

            Assert.Equal(keyKeyId.KeyId.ByteArrayToHex(), certKeyId.KeyId.ByteArrayToHex());

            byte[] data = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
            byte[] encrypted;

            using (X509Certificate2 fromLoader = loader.GetCertificate())
                using (X509Certificate2 fromBag = certBag.GetCertificate())
                    using (RSA loaderPub = fromLoader.GetRSAPublicKey())
                    {
                        Assert.Equal(fromLoader.RawData, fromBag.RawData);

                        encrypted = loaderPub.Encrypt(data, RSAEncryptionPadding.OaepSHA1);
                    }

            int bytesRead;

            using (RSA rsa = RSA.Create())
            {
                rsa.ImportEncryptedPkcs8PrivateKey(
                    loader.Password,
                    shroudedKeyBag.EncryptedPkcs8PrivateKey.Span,
                    out bytesRead);

                byte[] dec = rsa.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA1);
                Assert.Equal(data, dec);
            }

            Assert.Equal(shroudedKeyBag.EncryptedPkcs8PrivateKey.Length, bytesRead);
        }
예제 #12
0
        public static void ReadWithEncryptedContents()
        {
            var loader = (CertLoaderFromRawData)Certificates.RSAKeyTransfer_ExplicitSki;
            ReadOnlyMemory <byte> pfxData = loader.PfxData;

            Pkcs12Info info = Pkcs12Info.Decode(pfxData, out int bytesConsumed);

            Assert.Equal(pfxData.Length, bytesConsumed);

            Assert.Equal(Pkcs12IntegrityMode.Password, info.IntegrityMode);
            CheckMac(info, loader.Password);

            ReadOnlyCollection <Pkcs12SafeContents> authSafe = info.AuthenticatedSafe;

            Assert.Same(authSafe, info.AuthenticatedSafe);
            Assert.Equal(2, authSafe.Count);

            Assert.Equal(Pkcs12ConfidentialityMode.Password, authSafe[0].ConfidentialityMode);
            Assert.Equal(Pkcs12ConfidentialityMode.None, authSafe[1].ConfidentialityMode);

            Assert.ThrowsAny <CryptographicException>(
                () => authSafe[0].Decrypt(loader.Password.AsSpan().Slice(1)));

            Assert.Equal(Pkcs12ConfidentialityMode.Password, authSafe[0].ConfidentialityMode);
            authSafe[0].Decrypt(loader.Password);
            Assert.Equal(Pkcs12ConfidentialityMode.None, authSafe[0].ConfidentialityMode);

            List <Pkcs12SafeBag> safe0Bags = new List <Pkcs12SafeBag>(authSafe[0].GetBags());

            Assert.Equal(1, safe0Bags.Count);
            Pkcs12CertBag certBag = Assert.IsType <Pkcs12CertBag>(safe0Bags[0]);

            Assert.True(certBag.IsX509Certificate, "certBag.IsX509Certificate");
            Assert.InRange(certBag.EncodedCertificate.Length, loader.CerData.Length + 2, int.MaxValue);

            List <Pkcs12SafeBag> safe1Bags = new List <Pkcs12SafeBag>(authSafe[1].GetBags());

            Assert.Equal(1, safe0Bags.Count);
            Pkcs12ShroudedKeyBag shroudedKeyBag = Assert.IsType <Pkcs12ShroudedKeyBag>(safe1Bags[0]);

            byte[] data = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
            byte[] encrypted;

            using (X509Certificate2 fromLoader = loader.GetCertificate())
                using (X509Certificate2 fromBag = certBag.GetCertificate())
                    using (RSA loaderPub = fromLoader.GetRSAPublicKey())
                    {
                        Assert.Equal(fromLoader.RawData, fromBag.RawData);

                        encrypted = loaderPub.Encrypt(data, RSAEncryptionPadding.OaepSHA1);
                    }

            int bytesRead;

            using (RSA rsa = RSA.Create())
            {
                rsa.ImportEncryptedPkcs8PrivateKey(
                    loader.Password,
                    shroudedKeyBag.EncryptedPkcs8PrivateKey.Span,
                    out bytesRead);

                byte[] dec = rsa.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA1);
                Assert.Equal(data, dec);
            }

            Assert.Equal(shroudedKeyBag.EncryptedPkcs8PrivateKey.Length, bytesRead);
        }