Example #1
0
        public static void VerifyWriteNamedBitList_Generic_WithTag(AsnEncodingRules ruleSet)
        {
            AsnWriter objWriter = new AsnWriter(ruleSet);
            AsnWriter genWriter = new AsnWriter(ruleSet);
            Asn1Tag   tag       = new Asn1Tag(TagClass.ContextSpecific, 52);

            var flagsValue =
                ReadNamedBitList.X509KeyUsageCSharpStyle.DigitalSignature |
                ReadNamedBitList.X509KeyUsageCSharpStyle.KeyEncipherment |
                ReadNamedBitList.X509KeyUsageCSharpStyle.DataEncipherment;

            genWriter.WriteNamedBitList(flagsValue, tag);
            objWriter.WriteNamedBitList((Enum)flagsValue, tag);

            Verify(genWriter, objWriter.Encode().ByteArrayToHex());
        }
Example #2
0
        private byte[] EncryptContent(
            ContentInfo contentInfo,
            AlgorithmIdentifier contentEncryptionAlgorithm,
            out byte[] cek,
            out byte[] parameterBytes)
        {
            using (SymmetricAlgorithm alg = OpenAlgorithm(contentEncryptionAlgorithm))
                using (ICryptoTransform encryptor = alg.CreateEncryptor())
                {
                    cek = alg.Key;

                    if (alg is RC2)
                    {
                        Rc2CbcParameters rc2Params = new Rc2CbcParameters(alg.IV, alg.KeySize);

                        using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
                        {
                            rc2Params.Encode(writer);
                            parameterBytes = writer.Encode();
                        }
                    }
                    else
                    {
                        parameterBytes = EncodeOctetString(alg.IV);
                    }

                    byte[] toEncrypt = contentInfo.Content;

                    if (contentInfo.ContentType.Value == Oids.Pkcs7Data)
                    {
                        toEncrypt = EncodeOctetString(toEncrypt);
                        return(encryptor.OneShot(toEncrypt));
                    }
                    else
                    {
                        if (contentInfo.Content.Length == 0)
                        {
                            return(encryptor.OneShot(contentInfo.Content));
                        }
                        else
                        {
                            AsnReader reader = new AsnReader(contentInfo.Content, AsnEncodingRules.BER);
                            return(encryptor.OneShot(reader.PeekContentBytes().ToArray()));
                        }
                    }
                }
        }
        private static byte[] CreateRawAsn1(string policyOid, HashAlgorithmName algorithmNameForPolicy, ReadOnlySpan <byte> policyHashValue)
        {
            ThrowHelpers.CheckNullOrEempty(nameof(policyOid), policyOid);

            using AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER);
            asnWriter.PushSequence();
            asnWriter.WriteObjectIdentifier(policyOid);
            asnWriter.PushSequence();
            asnWriter.PushSequence();
            asnWriter.WriteObjectIdentifier(HashAlgorithmConvertor.ToOid(algorithmNameForPolicy));
            asnWriter.WriteNull();
            asnWriter.PopSequence();
            asnWriter.WriteOctetString(policyHashValue);
            asnWriter.PopSequence();
            asnWriter.PopSequence();
            return(asnWriter.Encode());
        }
Example #4
0
        public void SealWithoutIntegrity()
        {
            if (IsSealed)
            {
                throw new InvalidOperationException(SR.Cryptography_Pkcs12_PfxIsSealed);
            }

            AsnWriter contentsWriter = new AsnWriter(AsnEncodingRules.BER);
            AsnWriter writer         = new AsnWriter(AsnEncodingRules.BER);
            {
                contentsWriter.PushSequence();
                if (_contents != null)
                {
                    foreach (ContentInfoAsn contentInfo in _contents)
                    {
                        contentInfo.Encode(contentsWriter);
                    }
                }
                contentsWriter.PopSequence();

                // https://tools.ietf.org/html/rfc7292#section-4
                //
                // PFX ::= SEQUENCE {
                //   version    INTEGER {v3(3)}(v3,...),
                //   authSafe   ContentInfo,
                //   macData    MacData OPTIONAL
                // }
                writer.PushSequence();

                writer.WriteInteger(3);

                using (writer.PushSequence())
                {
                    writer.WriteObjectIdentifierForCrypto(Oids.Pkcs7Data);

                    using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0)))
                        using (writer.PushOctetString())
                        {
                            contentsWriter.CopyTo(writer);
                        }
                }

                writer.PopSequence();
                _sealedData = writer.Encode();
            }
        }
        public static void SerializeAlgorithmIdentifier()
        {
            AlgorithmIdentifier identifier = new AlgorithmIdentifier
            {
                Algorithm  = new Oid("2.16.840.1.101.3.4.2.1", "SHA-2-256"),
                Parameters = new byte[] { 5, 0 },
            };

            AsnWriter writer = AsnSerializer.Serialize(identifier, AsnEncodingRules.DER);

            const string ExpectedHex =
                "300D" +
                "0609608648016503040201" +
                "0500";

            Assert.Equal(ExpectedHex, writer.Encode().ByteArrayToHex());
        }
        private static byte[] CreateRawAsn1(string policyOid, HashAlgorithmName algorithmNameForPolicy, ReadOnlySpan <byte> policyHashValue)
        {
            if (policyOid == null)
            {
                throw new ArgumentNullException(nameof(policyOid));
            }

            using AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER);
            asnWriter.PushSequence();
            asnWriter.WriteObjectIdentifier(policyOid);
            asnWriter.PushSequence();
            asnWriter.WriteObjectIdentifier(HashAlgorithmConvertor.ToOid(algorithmNameForPolicy));
            asnWriter.WriteOctetString(policyHashValue);
            asnWriter.PopSequence();
            asnWriter.PopSequence();
            return(asnWriter.Encode());
        }
Example #7
0
        /// <summary>Exports the current key in the ECPrivateKey format.</summary>
        /// <returns>A byte array containing the ECPrivateKey representation of this key.</returns>
        /// <exception cref="CryptographicException">The key could not be exported.</exception>
        public virtual unsafe byte[] ExportECPrivateKey()
        {
            ECParameters ecParameters = ExportParameters(true);

            fixed(byte *privPin = ecParameters.D)
            {
                try
                {
                    AsnWriter writer = EccKeyFormatHelper.WriteECPrivateKey(ecParameters);
                    return(writer.Encode());
                }
                finally
                {
                    CryptographicOperations.ZeroMemory(ecParameters.D);
                }
            }
        }
        public void SepcialUTF8StringTest()
        {
            var writer = new AsnWriter();

            writer.WriteUTF8String("Swedish: Åå Ää Öö");
            writer.WriteUTF8String("Danish/Norway: Ææ Øø Åå");
            writer.WriteUTF8String("German/Finish: Ää Öö Üü");
            writer.WriteUTF8String("Greek lower: αβγδϵζηθικλμνξοπρστυϕχψω");
            writer.WriteUTF8String("Greek upper: ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ");
            writer.WriteUTF8String("Russian: АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя");

            var content = PostchainUtil.ByteArrayToString(writer.Encode()).ToUpper();

            var expected = "0C17537765646973683A20C385C3A520C384C3A420C396C3B60C1D44616E6973682F4E6F727761793A20C386C3A620C398C3B820C385C3A50C1D4765726D616E2F46696E6973683A20C384C3A420C396C3B620C39CC3BC0C3D477265656B206C6F7765723A20CEB1CEB2CEB3CEB4CFB5CEB6CEB7CEB8CEB9CEBACEBBCEBCCEBDCEBECEBFCF80CF81CF83CF84CF85CF95CF87CF88CF890C3D477265656B2075707065723A20CE91CE92CE93CE94CE95CE96CE97CE98CE99CE9ACE9BCE9CCE9DCE9ECE9FCEA0CEA1CEA3CEA4CEA5CEA6CEA7CEA8CEA90C81895275737369616E3A20D090D0B0D091D0B1D092D0B2D093D0B3D094D0B4D095D0B5D081D191D096D0B6D097D0B7D098D0B8D099D0B9D09AD0BAD09BD0BBD09CD0BCD09DD0BDD09ED0BED09FD0BFD0A1D181D0A2D182D0A3D183D0A4D184D0A5D185D0A6D186D0A7D187D0A8D188D0A9D189D0AAD18AD0ABD18BD0ACD18CD0ADD18DD0AED18ED0AFD18F";

            Assert.Equal(expected, content);
        }
Example #9
0
        public static void VerifyWriteEnumeratedValue_Object(PublicEncodingRules ruleSet)
        {
            using (AsnWriter objWriter = new AsnWriter((AsnEncodingRules)ruleSet))
                using (AsnWriter genWriter = new AsnWriter((AsnEncodingRules)ruleSet))
                {
                    genWriter.WriteEnumeratedValue(ReadEnumerated.UIntBacked.Fluff);
                    objWriter.WriteEnumeratedValue((object)ReadEnumerated.UIntBacked.Fluff);

                    genWriter.WriteEnumeratedValue(ReadEnumerated.SByteBacked.Fluff);
                    objWriter.WriteEnumeratedValue((object)ReadEnumerated.SByteBacked.Fluff);

                    genWriter.WriteEnumeratedValue(ReadEnumerated.ULongBacked.Fluff);
                    objWriter.WriteEnumeratedValue((object)ReadEnumerated.ULongBacked.Fluff);

                    Verify(objWriter, genWriter.Encode().ByteArrayToHex());
                }
        }
Example #10
0
        public static void InitialCapacity_UnderCapacity()
        {
            ReadOnlySpan <byte> value  = new byte[] { 0x04, 0x01, 0x01 };
            AsnWriter           writer = new AsnWriter(AsnEncodingRules.DER, initialCapacity: 8);

            writer.WriteEncodedValue(value);

            byte[]? buffer = PeekRawBuffer(writer);
            Assert.Equal(8, buffer?.Length);

            byte[] encoded = writer.Encode();
            AssertExtensions.SequenceEqual(value, encoded);

            writer.Reset();
            buffer = PeekRawBuffer(writer);
            Assert.Equal(8, buffer?.Length);
        }
Example #11
0
        public byte[] Encode()
        {
            if (!_hasData)
            {
                throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotSigned);
            }

            try
            {
                using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
                {
                    _signedData.Encode(writer);
                    return(PkcsHelpers.EncodeContentInfo(writer.Encode(), Oids.Pkcs7Signed));
                }
            }
            catch (CryptographicException) when(!Detached)
            {
                // If we can't write the contents back out then the most likely culprit is an
                // indefinite length encoding in the content field.  To preserve as much input data
                // as possible while still maintaining our expectations of sorting any SET OF values,
                // do the following:
                // * Write the DER normalized version of the SignedData in detached mode.
                // * BER-decode that structure
                // * Copy the content field over
                // * BER-write the modified structure.

                SignedDataAsn copy = _signedData;

                copy.EncapContentInfo.Content = null;
                Debug.Assert(_signedData.EncapContentInfo.Content != null);

                using (AsnWriter detachedWriter = new AsnWriter(AsnEncodingRules.DER))
                {
                    copy.Encode(detachedWriter);
                    copy = SignedDataAsn.Decode(detachedWriter.Encode(), AsnEncodingRules.BER);
                }

                copy.EncapContentInfo.Content = _signedData.EncapContentInfo.Content;

                using (AsnWriter attachedWriter = new AsnWriter(AsnEncodingRules.BER))
                {
                    copy.Encode(attachedWriter);
                    return(PkcsHelpers.EncodeContentInfo(attachedWriter.Encode(), Oids.Pkcs7Signed));
                }
            }
        }
Example #12
0
        public byte[] Encrypt(ReadOnlySpan <byte> passwordBytes, PbeParameters pbeParameters)
        {
            if (pbeParameters == null)
            {
                throw new ArgumentNullException(nameof(pbeParameters));
            }

            PasswordBasedEncryption.ValidatePbeParameters(
                pbeParameters,
                ReadOnlySpan <char> .Empty,
                passwordBytes);

            AsnWriter pkcs8  = WritePkcs8();
            AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(passwordBytes, pkcs8, pbeParameters);

            return(writer.Encode());
        }
Example #13
0
        internal static byte[] EncodeContentInfo(
            ReadOnlyMemory <byte> content,
            string contentType,
            AsnEncodingRules ruleSet = AsnEncodingRules.DER)
        {
            ContentInfoAsn contentInfo = new ContentInfoAsn
            {
                ContentType = contentType,
                Content     = content,
            };

            using (AsnWriter writer = new AsnWriter(ruleSet))
            {
                contentInfo.Encode(writer);
                return(writer.Encode());
            }
        }
Example #14
0
        public X509Extension Build(bool critical = false)
        {
            AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);

            using (writer.PushSequence())
            {
                foreach (byte[] encodedName in _encodedNames)
                {
                    writer.WriteEncodedValue(encodedName);
                }
            }

            return(new X509Extension(
                       Oids.SubjectAltName,
                       writer.Encode(),
                       critical));
        }
Example #15
0
        private static byte[] ExportRSAPublicKey(RSA rsa)
        {
            RSAParameters rsaParameters = rsa.ExportParameters(false);

            if (rsaParameters.Modulus == null || rsaParameters.Exponent == null)
            {
                throw new CryptographicException("Invalid RSA Parameters.");
            }

            AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);

            writer.PushSequence();
            writer.WriteKeyParameterInteger(rsaParameters.Modulus);
            writer.WriteKeyParameterInteger(rsaParameters.Exponent);
            writer.PopSequence();
            return(writer.Encode());
        }
Example #16
0
        public static ReadOnlyMemory <byte> Encode(Oid oid, KrbApReq krbApReq)
        {
            using (var writer = new AsnWriter(AsnEncodingRules.DER))
            {
                writer.PushSequence(ApplicationTag);

                writer.WriteObjectIdentifier(oid);

                writer.WriteEncodedValue(new byte[] { 0x01, 0x0 });

                writer.WriteEncodedValue(krbApReq.EncodeApplication().Span);

                writer.PopSequence(ApplicationTag);

                return(writer.Encode());
            }
        }
Example #17
0
        /// <summary>
        /// Build the Authority information Access extension.
        /// </summary>
        /// <param name="caIssuerUrls">Array of CA Issuer Urls</param>
        /// <param name="ocspResponder">optional, the OCSP responder </param>
        private static X509Extension BuildX509AuthorityInformationAccess(
            string[] caIssuerUrls,
            string ocspResponder = null
            )
        {
            if (String.IsNullOrEmpty(ocspResponder) &&
                (caIssuerUrls == null ||
                 (caIssuerUrls != null && caIssuerUrls.Length == 0)))
            {
                throw new ArgumentNullException(nameof(caIssuerUrls), "One CA Issuer Url or OCSP responder is required for the extension.");
            }

            var     context0             = new Asn1Tag(TagClass.ContextSpecific, 0, true);
            Asn1Tag generalNameUriChoice = new Asn1Tag(TagClass.ContextSpecific, 6);

            using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
            {
                writer.PushSequence();
                if (caIssuerUrls != null)
                {
                    foreach (var caIssuerUrl in caIssuerUrls)
                    {
                        writer.PushSequence();
                        writer.WriteObjectIdentifier("1.3.6.1.5.5.7.48.2");
                        writer.WriteCharacterString(
                            generalNameUriChoice,
                            UniversalTagNumber.IA5String,
                            caIssuerUrl);
                        writer.PopSequence();
                    }
                }
                if (!String.IsNullOrEmpty(ocspResponder))
                {
                    writer.PushSequence();
                    writer.WriteObjectIdentifier("1.3.6.1.5.5.7.48.1");
                    writer.WriteCharacterString(
                        generalNameUriChoice,
                        UniversalTagNumber.IA5String,
                        ocspResponder);
                    writer.PopSequence();
                }
                writer.PopSequence();
                return(new X509Extension("1.3.6.1.5.5.7.1.1", writer.Encode(), false));
            }
        }
Example #18
0
        public void AddAlgorithmProtectAttribute()
        {
            var writer  = new AsnWriter(AsnEncodingRules.DER);
            var algAttr = default(CmsAlgorithmProtectAttributeAsn);

            algAttr.DigestAlgorithm            = default(AlgorithmIdentifierAsn);
            algAttr.DigestAlgorithm.Algorithm  = new Oid(SigningPolicy.DigestAlgorithmOID);
            algAttr.DigestAlgorithm.Parameters = SigningPolicy.DigestAlgorithmParameters;
            var sigAlg = default(AlgorithmIdentifierAsn);

            sigAlg.Algorithm           = new Oid(SigningPolicy.EncryptionAlgorithmOID, SigningPolicy.SignatureAlgorithmName);
            sigAlg.Parameters          = SigningPolicy.SigningParameters;
            algAttr.SignatureAlgorithm = sigAlg;
            algAttr.Encode(writer);
            var payload = writer.Encode();

            SignedAttributes.Add(new AsnEncodedData(new Oid(Oids.IdAaCmsAlgorithmProtect), payload));
        }
        public override byte[] GetSignatureAlgorithmIdentifier(HashAlgorithmName hashAlgorithm)
        {
            if (hashAlgorithm != HashAlgorithmName.Gost3411)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(hashAlgorithm),
                          hashAlgorithm,
                          SR.Format(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name));
            }

            using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
            {
                writer.PushSequence();
                writer.WriteObjectIdentifier(Oids.Gost3411_3410EL);
                writer.PopSequence();
                return(writer.Encode());
            }
        }
Example #20
0
        public virtual byte[] EncodeX509BasicConstraints2Extension(
            bool certificateAuthority,
            bool hasPathLengthConstraint,
            int pathLengthConstraint)
        {
            BasicConstraintsAsn constraints = default;

            constraints.CA = certificateAuthority;
            if (hasPathLengthConstraint)
            {
                constraints.PathLengthConstraint = pathLengthConstraint;
            }

            AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);

            constraints.Encode(writer);
            return(writer.Encode());
        }
Example #21
0
        public virtual byte[] EncodeX509SubjectKeyIdentifierExtension(ReadOnlySpan <byte> subjectKeyIdentifier)
        {
            // https://tools.ietf.org/html/rfc5280#section-4.2.1.2
            //
            // subjectKeyIdentifier EXTENSION ::= {
            //     SYNTAX SubjectKeyIdentifier
            //     IDENTIFIED BY id - ce - subjectKeyIdentifier
            // }
            //
            // SubjectKeyIdentifier::= KeyIdentifier
            //
            // KeyIdentifier ::= OCTET STRING

            AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);

            writer.WriteOctetString(subjectKeyIdentifier);
            return(writer.Encode());
        }
        public virtual byte[] EncodeX509BasicConstraints2Extension(
            bool certificateAuthority,
            bool hasPathLengthConstraint,
            int pathLengthConstraint)
        {
            BasicConstraintsAsn constraints = new BasicConstraintsAsn();

            constraints.CA = certificateAuthority;
            if (hasPathLengthConstraint)
            {
                constraints.PathLengthConstraint = pathLengthConstraint;
            }

            using (AsnWriter writer = AsnSerializer.Serialize(constraints, AsnEncodingRules.DER))
            {
                return(writer.Encode());
            }
        }
        /// <summary>
        /// Convert Ieee1363 format of (r, s) to Der format
        /// </summary>
        public static byte[] ConvertIeee1363ToDer(ReadOnlySpan <byte> input)
        {
            Debug.Assert(input.Length % 2 == 0);
            Debug.Assert(input.Length > 1);

            // Input is (r, s), each of them exactly half of the array.
            // Output is the DER encoded value of CONSTRUCTEDSEQUENCE(INTEGER(r), INTEGER(s)).
            int halfLength = input.Length / 2;

            using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
            {
                writer.PushSequence();
                writer.WriteKeyParameterInteger(input.Slice(0, halfLength));
                writer.WriteKeyParameterInteger(input.Slice(halfLength, halfLength));
                writer.PopSequence();
                return(writer.Encode());
            }
        }
Example #24
0
        public static void CopyTo_Success(AsnEncodingRules ruleSet)
        {
            AsnWriter source = new AsnWriter(ruleSet);
            AsnWriter dest   = new AsnWriter(AsnEncodingRules.BER);

            Assert.True(source.EncodedValueEquals(dest));

            source.WriteBoolean(false);
            Assert.False(source.EncodedValueEquals(dest));

            source.CopyTo(dest);
            Assert.True(source.EncodedValueEquals(dest));

            Assert.Equal(source.Encode(), dest.Encode());

            source.CopyTo(dest);
            Assert.False(source.EncodedValueEquals(dest));
        }
Example #25
0
        public static void SerializeExplicitDefaultValue(int version, string expectedHex)
        {
            ExplicitDefaultAsn data = new ExplicitDefaultAsn {
                Version = version
            };

            byte[] encoded;

            using (AsnWriter writer = AsnSerializer.Serialize(data, AsnEncodingRules.DER))
            {
                encoded = writer.Encode();
                Assert.Equal(expectedHex, encoded.ByteArrayToHex());
            }

            // Deserialize the data back.
            data = AsnSerializer.Deserialize <ExplicitDefaultAsn>(encoded, AsnEncodingRules.DER);
            Assert.Equal(version, data.Version);
        }
Example #26
0
        public static void WriteAnyValueWithExpectedTag()
        {
            byte[] anyValue = "3003010100".HexToByteArray();

            var data = new AnyWithExpectedTag
            {
                Id   = "0.0",
                Data = anyValue,
            };

            AsnWriter writer = AsnSerializer.Serialize(data, AsnEncodingRules.DER);

            Assert.Equal("30080601003003010100", writer.Encode().ByteArrayToHex());

            anyValue[0] = 0xA0;

            Assert.Throws <CryptographicException>(() => AsnSerializer.Serialize(data, AsnEncodingRules.DER));
        }
        private static void ReencodeIfUsingIndefiniteLengthEncodingOnOuterStructure(ref byte[] encodedContent)
        {
            AsnReader reader = new AsnReader(encodedContent, AsnEncodingRules.BER);
            Asn1Tag   tag    = reader.ReadTagAndLength(out int?contentsLength, out int _);

            if (contentsLength != null)
            {
                // definite length, do nothing
                return;
            }

            using (AsnWriter writer = new AsnWriter(AsnEncodingRules.BER))
            {
                // Tag doesn't matter here as we won't write it into the document
                writer.WriteOctetString(reader.PeekContentBytes().Span);
                encodedContent = writer.Encode();
            }
        }
        public virtual byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
        {
            // The CapiSha1 value is the SHA-1 of the SubjectPublicKeyInfo field, inclusive
            // of the DER structural bytes.

            SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn();

            spki.Algorithm = new AlgorithmIdentifierAsn {
                Algorithm = key.Oid, Parameters = key.EncodedParameters.RawData
            };
            spki.SubjectPublicKey = key.EncodedKeyValue.RawData;

            using (AsnWriter writer = AsnSerializer.Serialize(spki, AsnEncodingRules.DER))
                using (SHA1 hash = SHA1.Create())
                {
                    return(hash.ComputeHash(writer.Encode()));
                }
        }
Example #29
0
        internal static byte[] EncodeContentInfo <T>(
            T value,
            string contentType,
            AsnEncodingRules ruleSet = AsnEncodingRules.DER)
        {
            using (AsnWriter innerWriter = AsnSerializer.Serialize(value, ruleSet))
            {
                ContentInfoAsn content = new ContentInfoAsn
                {
                    ContentType = contentType,
                    Content     = innerWriter.Encode(),
                };

                using (AsnWriter outerWriter = AsnSerializer.Serialize(content, ruleSet))
                {
                    return(outerWriter.Encode());
                }
            }
        }
Example #30
0
        private static void WriteRSAPublicKeyCore(AsnEncodingRules ruleSet, string expectedHex)
        {
            using (AsnWriter innerWriter = new AsnWriter(ruleSet))
            {
                byte[] paddedBigEndianN = (
                    "00" +
                    "AF81C1CBD8203F624A539ED6608175372393A2837D4890E48A19DED369731156" +
                    "20968D6BE0D3DAA38AA777BE02EE0B6B93B724E8DCC12B632B4FA80BBC925BCE" +
                    "624F4CA7CC606306B39403E28C932D24DD546FFE4EF6A37F10770B2215EA8CBB" +
                    "5BF427E8C4D89B79EB338375100C5F83E55DE9B4466DDFBEEE42539AEF33EF18" +
                    "7B7760C3B1A1B2103C2D8144564A0C1039A09C85CF6B5974EB516FC8D6623C94" +
                    "AE3A5A0BB3B4C792957D432391566CF3E2A52AFB0C142B9E0681B8972671AF2B" +
                    "82DD390A39B939CF719568687E4990A63050CA7768DCD6B378842F18FDB1F6D9" +
                    "FF096BAF7BEB98DCF930D66FCFD503F58D41BFF46212E24E3AFC45EA42BD8847").HexToByteArray();

                // Now it's padded little-endian.
                Array.Reverse(paddedBigEndianN);
                BigInteger n = new BigInteger(paddedBigEndianN);
                const long e = 8589935681;

                innerWriter.PushSequence();
                innerWriter.WriteInteger(n);
                innerWriter.WriteInteger(e);
                innerWriter.PopSequence();

                using (AsnWriter outerWriter = new AsnWriter(ruleSet))
                {
                    // RSAPublicKey
                    outerWriter.PushSequence();

                    // AlgorithmIdentifier
                    outerWriter.PushSequence();
                    outerWriter.WriteObjectIdentifier("1.2.840.113549.1.1.1");
                    outerWriter.WriteNull();
                    outerWriter.PopSequence();

                    outerWriter.WriteBitString(innerWriter.Encode());
                    outerWriter.PopSequence();

                    Verify(outerWriter, expectedHex);
                }
            }
        }