示例#1
0
        public static void ReadIndefiniteLengthCustomTaggedStrings()
        {
            byte[] inputData = (
                // (constructed) SEQUENCE (indefinite)
                "3080" +
                // (constructed) CONTEXT-SPECIFIC 0 (indefinite)
                "A080" +
                // OCTET STRING (3): 020100
                "0403020100" +
                // EoC ([0])
                "0000" +
                // (constructed) CONTEXT-SPECIFIC 1 (indefinite)
                "A180" +
                // BIT STRING (4) (0 unused bits): 010203
                "030400010203" +
                // EoC ([1])
                "0000" +
                // EoC (SEQUENCE)
                "0000").HexToByteArray();

            CustomTaggedBinaryStrings parsed =
                AsnSerializer.Deserialize <CustomTaggedBinaryStrings>(inputData, AsnEncodingRules.BER);

            Assert.Equal("020100", parsed.OctetString.ByteArrayToHex());
            Assert.Equal("010203", parsed.BitString.ByteArrayToHex());
        }
示例#2
0
        private SignerInfoCollection GetCounterSigners(AttributeAsn[] unsignedAttrs)
        {
            // Since each "attribute" can have multiple "attribute values" there's no real
            // correlation to a predictive size here.
            List <SignerInfo> signerInfos = new List <SignerInfo>();

            foreach (AttributeAsn attributeAsn in unsignedAttrs)
            {
                if (attributeAsn.AttrType.Value == Oids.CounterSigner)
                {
                    AsnReader reader     = new AsnReader(attributeAsn.AttrValues, AsnEncodingRules.BER);
                    AsnReader collReader = reader.ReadSetOf();

                    if (reader.HasData)
                    {
                        throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                    }

                    while (collReader.HasData)
                    {
                        SignerInfoAsn parsedData =
                            AsnSerializer.Deserialize <SignerInfoAsn>(collReader.GetEncodedValue(), AsnEncodingRules.BER);

                        SignerInfo signerInfo = new SignerInfo(ref parsedData, _document)
                        {
                            _parentSignerInfo = this
                        };

                        signerInfos.Add(signerInfo);
                    }
                }
            }

            return(new SignerInfoCollection(signerInfos.ToArray()));
        }
示例#3
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 = AsnSerializer.Serialize(rc2Params, AsnEncodingRules.DER))
                        {
                            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));
                }
        }
示例#4
0
        public static void ReadEcPublicKey()
        {
            const string PublicKeyValue =
                "04" +
                "2363DD131DA65E899A2E63E9E05E50C830D4994662FFE883DB2B9A767DCCABA2" +
                "F07081B5711BE1DEE90DFC8DE17970C2D937A16CD34581F52B8D59C9E9532D13";

            const string InputHex =
                "3059" +
                "3013" +
                "06072A8648CE3D0201" +
                "06082A8648CE3D030107" +
                "0342" +
                "00" +
                PublicKeyValue;

            byte[] inputData = InputHex.HexToByteArray();

            var spki = AsnSerializer.Deserialize <SubjectPublicKeyInfo>(
                inputData,
                AsnEncodingRules.DER);

            Assert.Equal("1.2.840.10045.2.1", spki.AlgorithmIdentifier.Algorithm.Value);
            Assert.Equal(PublicKeyValue, spki.PublicKey.ByteArrayToHex());

            AsnReader reader   = new AsnReader(spki.AlgorithmIdentifier.Parameters, AsnEncodingRules.DER);
            string    curveOid = reader.ReadObjectIdentifierAsString();

            Assert.False(reader.HasData, "reader.HasData");
            Assert.Equal("1.2.840.10045.3.1.7", curveOid);
        }
示例#5
0
        public static void ReadFlexibleString_StructHybrid()
        {
            const string BmpInputHex  = "1E0400480069";
            const string Utf8InputHex = "0C024869";
            const string Ia5InputHex  = "16024869";

            var fs1 = AsnSerializer.Deserialize <FlexibleStringStructHybrid>(
                BmpInputHex.HexToByteArray(),
                AsnEncodingRules.DER);

            var fs2 = AsnSerializer.Deserialize <FlexibleStringStructHybrid>(
                Utf8InputHex.HexToByteArray(),
                AsnEncodingRules.DER);

            var fs3 = AsnSerializer.Deserialize <FlexibleStringStructHybrid>(
                Ia5InputHex.HexToByteArray(),
                AsnEncodingRules.DER);

            Assert.Null(fs1.DirectoryString?.Utf8String);
            Assert.Null(fs1.Ascii);
            Assert.Null(fs2.DirectoryString?.BmpString);
            Assert.Null(fs2.Ascii);
            Assert.Null(fs3.DirectoryString?.BmpString);
            Assert.Null(fs3.DirectoryString?.Utf8String);
            Assert.Null(fs3.DirectoryString);
            Assert.Equal("Hi", fs1.DirectoryString?.BmpString);
            Assert.Equal("Hi", fs2.DirectoryString?.Utf8String);
            Assert.Equal("Hi", fs3.Ascii);
        }
示例#6
0
        public static void SerializeChoice_NoSelection()
        {
            DirectoryStringClass directoryString = new DirectoryStringClass();

            Assert.ThrowsAny <CryptographicException>(
                () => AsnSerializer.Serialize(directoryString, AsnEncodingRules.DER));
        }
示例#7
0
        internal Pkcs12SecretBag(Oid secretTypeOid, ReadOnlyMemory <byte> secretValue)
            : this(EncodeBagValue(secretTypeOid, secretValue))
        {
            _secretTypeOid = new Oid(secretTypeOid);

            _decoded = AsnSerializer.Deserialize <SecretBagAsn>(EncodedBagValue, AsnEncodingRules.BER);
        }
示例#8
0
        public static void SerializeChoice_Null()
        {
            DirectoryStringClass directoryString = default;
            AsnWriter            writer          = AsnSerializer.Serialize(directoryString, AsnEncodingRules.DER);

            Assert.Equal("0500", writer.Encode().ByteArrayToHex());
        }
        private static bool TryDecode(
            ReadOnlyMemory <byte> source,
            bool ownsMemory,
            out Rfc3161TstInfo tstInfo,
            out int bytesConsumed,
            out byte[] copiedBytes)
        {
            // https://tools.ietf.org/html/rfc3161#section-2.4.2
            // The eContent SHALL be the DER-encoded value of TSTInfo.
            AsnReader reader = new AsnReader(source, AsnEncodingRules.DER);

            try
            {
                ReadOnlyMemory <byte> firstElement = reader.PeekEncodedValue();

                if (ownsMemory)
                {
                    copiedBytes = null;
                }
                else
                {
                    // Copy the data so no ReadOnlyMemory values are pointing back to user data.
                    copiedBytes  = firstElement.ToArray();
                    firstElement = copiedBytes;
                }

                Rfc3161TstInfo parsedInfo = AsnSerializer.Deserialize <Rfc3161TstInfo>(
                    firstElement,
                    AsnEncodingRules.DER);

                // The deserializer doesn't do bounds checks.
                // Micros and Millis are defined as (1..999)
                // Seconds doesn't define that it's bounded by 0,
                // but negative accuracy doesn't make sense.
                //
                // (Reminder to readers: a null int? with an inequality operator
                // has the value false, so if accuracy is missing, or millis or micro is missing,
                // then the respective checks return false and don't throw).
                if (parsedInfo.Accuracy?.Micros > 999 ||
                    parsedInfo.Accuracy?.Micros < 1 ||
                    parsedInfo.Accuracy?.Millis > 999 ||
                    parsedInfo.Accuracy?.Millis < 1 ||
                    parsedInfo.Accuracy?.Seconds < 0)
                {
                    throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                }

                tstInfo       = parsedInfo;
                bytesConsumed = firstElement.Length;
                return(true);
            }
            catch (CryptographicException)
            {
                tstInfo       = null;
                bytesConsumed = 0;
                copiedBytes   = null;
                return(false);
            }
        }
示例#10
0
        private bool ProcessResponse(
            ReadOnlyMemory <byte> source,
            out Rfc3161TimestampToken token,
            out Rfc3161RequestResponseStatus status,
            out int bytesConsumed,
            bool shouldThrow)
        {
            status = Rfc3161RequestResponseStatus.Unknown;
            token  = null;

            Rfc3161TimeStampResp resp;

            try
            {
                resp = AsnSerializer.Deserialize <Rfc3161TimeStampResp>(source, AsnEncodingRules.DER, out bytesConsumed);
            }
            catch (CryptographicException) when(!shouldThrow)
            {
                bytesConsumed = 0;
                status        = Rfc3161RequestResponseStatus.DoesNotParse;
                return(false);
            }

            // bytesRead will be set past this point

            PkiStatus pkiStatus = (PkiStatus)resp.Status.Status;

            if (pkiStatus != PkiStatus.Granted &&
                pkiStatus != PkiStatus.GrantedWithMods)
            {
                if (shouldThrow)
                {
                    throw new CryptographicException(
                              SR.Format(
                                  SR.Cryptography_TimestampReq_Failure,
                                  pkiStatus,
                                  resp.Status.FailInfo.GetValueOrDefault()));
                }

                status = Rfc3161RequestResponseStatus.RequestFailed;
                return(false);
            }

            if (!Rfc3161TimestampToken.TryDecode(resp.TimeStampToken.GetValueOrDefault(), out token, out _))
            {
                if (shouldThrow)
                {
                    throw new CryptographicException(SR.Cryptography_TimestampReq_BadResponse);
                }

                bytesConsumed = 0;
                status        = Rfc3161RequestResponseStatus.DoesNotParse;
                return(false);
            }

            status = ValidateResponse(token, shouldThrow);
            return(status == Rfc3161RequestResponseStatus.Accepted);
        }
示例#11
0
        public static void ReadMicrosoftDotCom()
        {
            byte[] buf = Convert.FromBase64String(MicrosoftDotComBase64);

            Certificate cert = AsnSerializer.Deserialize <Certificate>(
                buf,
                AsnEncodingRules.DER);

            ref TbsCertificate          tbsCertificate = ref cert.TbsCertificate;
示例#12
0
        public static void DirectoryStringClass_AsNull()
        {
            byte[] inputBytes = { 0x05, 0x00 };

            DirectoryStringClass ds = AsnSerializer.Deserialize <DirectoryStringClass>(
                inputBytes,
                AsnEncodingRules.DER);

            Assert.Null(ds);
        }
示例#13
0
        public override Oid GetEncodedMessageType(byte[] encodedMessage)
        {
            AsnReader reader = new AsnReader(encodedMessage, AsnEncodingRules.BER);

            ContentInfoAsn contentInfo = AsnSerializer.Deserialize <ContentInfoAsn>(
                reader.GetEncodedValue(),
                AsnEncodingRules.BER);

            return(new Oid(contentInfo.ContentType));
        }
示例#14
0
        public static void TooMuchData()
        {
            // This is { IA5String("IA5"), UTF8String("UTF8") }, which is the opposite
            // of the field order of OptionalValues.  SO it will see the UTF8String as null,
            // then the IA5String as present, but then data remains.
            byte[] inputData = "300B16034941350C0455544638".HexToByteArray();

            Assert.Throws <CryptographicException>(
                () => AsnSerializer.Deserialize <OptionalValues>(inputData, AsnEncodingRules.BER));
        }
示例#15
0
        internal void Decode(ReadOnlyMemory <byte> encodedMessage)
        {
            // Windows (and thus NetFx) reads the leading data and ignores extra.
            // So use the Deserialize overload which doesn't throw on extra data.
            ContentInfoAsn contentInfo = AsnSerializer.Deserialize <ContentInfoAsn>(
                encodedMessage,
                AsnEncodingRules.BER,
                out int bytesRead);

            if (contentInfo.ContentType != Oids.Pkcs7Signed)
            {
                throw new CryptographicException(SR.Cryptography_Cms_InvalidMessageType);
            }

            // Hold a copy of the SignedData memory so we are protected against memory reuse by the caller.
            _heldData        = contentInfo.Content.ToArray();
            _signedData      = AsnSerializer.Deserialize <SignedDataAsn>(_heldData, AsnEncodingRules.BER);
            _contentType     = _signedData.EncapContentInfo.ContentType;
            _hasPkcs7Content = false;

            if (!Detached)
            {
                ReadOnlyMemory <byte>?content = _signedData.EncapContentInfo.Content;
                ReadOnlyMemory <byte> contentValue;

                if (content.HasValue)
                {
                    contentValue = GetContent(content.Value, _contentType);
                    // If no OCTET STRING was stripped off, we have PKCS7 interop concerns.
                    _hasPkcs7Content = content.Value.Length == contentValue.Length;
                }
                else
                {
                    contentValue = ReadOnlyMemory <byte> .Empty;
                }

                // This is in _heldData, so we don't need a defensive copy.
                _heldContent = contentValue;

                // The ContentInfo object/property DOES need a defensive copy, because
                // a) it is mutable by the user, and
                // b) it is no longer authoritative
                //
                // (and c: it takes a byte[] and we have a ReadOnlyMemory<byte>)
                ContentInfo = new ContentInfo(new Oid(_contentType), contentValue.ToArray());
            }
            else
            {
                // Hold a defensive copy of the content bytes, (Windows/NetFx compat)
                _heldContent = ContentInfo.Content.CloneByteArray();
            }

            Version  = _signedData.Version;
            _hasData = true;
        }
示例#16
0
        public static void SerializeNullOidString()
        {
            AnyWithExpectedTag anyVal = new AnyWithExpectedTag
            {
                Id   = null,
                Data = "3000".HexToByteArray(),
            };

            Assert.Throws <CryptographicException>(
                () => AsnSerializer.Serialize(anyVal, AsnEncodingRules.DER));
        }
示例#17
0
        public static void SerializeChoice_WithinChoice6()
        {
            var hybrid = new FlexibleStringStructHybrid
            {
                Ascii = "IA5",
            };

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

            Assert.Equal("1603494135", writer.Encode().ByteArrayToHex());
        }
示例#18
0
        public static void SerializeNamedBitList()
        {
            var flagsContainer = new NamedBitListModeVariants
            {
                DefaultMode = SomeFlagsEnum.BitEleven | SomeFlagsEnum.BitTwo | SomeFlagsEnum.BitFourteen
            };

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

            Assert.Equal("30050303012012", writer.Encode().ByteArrayToHex());
        }
示例#19
0
        public static void SerializeChoice_First()
        {
            DirectoryStringClass directoryString = new DirectoryStringClass
            {
                Utf8String = "UTF8",
            };

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

            Assert.Equal("0C0455544638", writer.Encode().ByteArrayToHex());
        }
示例#20
0
        public static void Deserialize_ContextSpecific_Choice()
        {
            byte[] inputBytes = { 0x82, 0x00 };

            ContextSpecificChoice choice = AsnSerializer.Deserialize <ContextSpecificChoice>(
                inputBytes,
                AsnEncodingRules.DER);

            Assert.Null(choice.Utf8String);
            Assert.Equal(string.Empty, choice.IA5String);
        }
示例#21
0
        public static void SerializeChoice_Third()
        {
            DirectoryStringClass directoryString = new DirectoryStringClass
            {
                PrintableString = "Printable",
            };

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

            Assert.Equal("13095072696E7461626C65", writer.Encode().ByteArrayToHex());
        }
示例#22
0
        public static void SerializeChoice_MultipleSelections()
        {
            DirectoryStringClass directoryString = new DirectoryStringClass
            {
                BmpString       = "BMP",
                PrintableString = "Printable",
            };

            Assert.ThrowsAny <CryptographicException>(
                () => AsnSerializer.Serialize(directoryString, AsnEncodingRules.DER));
        }
示例#23
0
        public static void Choice_CycleRoot_Throws()
        {
            byte[] inputBytes = { 0x01, 0x01, 0x00 };

            Assert.Throws <AsnSerializationConstraintException>(
                () =>
                AsnSerializer.Deserialize <CycleRoot>(
                    inputBytes,
                    AsnEncodingRules.DER)
                );
        }
示例#24
0
        public static void SerializeChoice_Second()
        {
            DirectoryStringClass directoryString = new DirectoryStringClass
            {
                BmpString = "BMP",
            };

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

            Assert.Equal("1E060042004D0050", writer.Encode().ByteArrayToHex());
        }
示例#25
0
        public static void SerializeNullAlgorithmIdentifier()
        {
            AlgorithmIdentifier identifier = new AlgorithmIdentifier
            {
                Algorithm  = new Oid(null, "SHA-2-256"),
                Parameters = new byte[] { 5, 0 },
            };

            Assert.Throws <CryptographicException>(
                () => AsnSerializer.Serialize(identifier, AsnEncodingRules.DER));
        }
示例#26
0
        internal static void Decode(AsnReader reader, out PssParamsAsn decoded)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            ReadOnlyMemory <byte> value = reader.GetEncodedValue();

            decoded = AsnSerializer.Deserialize <PssParamsAsn>(value, reader.RuleSet);
        }
        public virtual void DecodeX509BasicConstraints2Extension(
            byte[] encoded,
            out bool certificateAuthority,
            out bool hasPathLengthConstraint,
            out int pathLengthConstraint)
        {
            BasicConstraintsAsn constraints = AsnSerializer.Deserialize <BasicConstraintsAsn>(encoded, AsnEncodingRules.BER);

            certificateAuthority    = constraints.CA;
            hasPathLengthConstraint = constraints.PathLengthConstraint.HasValue;
            pathLengthConstraint    = constraints.PathLengthConstraint.GetValueOrDefault();
        }
示例#28
0
        public static void SerializeExplicitValue()
        {
            var data = new ExplicitValueStruct
            {
                ExplicitInt = 3,
                ImplicitInt = 0x17,
            };

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

            Assert.Equal("3008A003020103020117", writer.Encode().ByteArrayToHex());
        }
示例#29
0
        public static void WriteOptionals(string expectedHex, bool hasUtf8, bool hasIa5)
        {
            var data = new OptionalValues
            {
                Utf8String = hasUtf8 ? "UTF8" : null,
                IA5String  = hasIa5 ? "IA5" : null,
            };

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

            Assert.Equal(expectedHex, writer.Encode().ByteArrayToHex());
        }
示例#30
0
        public static void WriteNegativeIntegers()
        {
            BigIntegers bigIntegers = new BigIntegers
            {
                First  = -273,
                Second = new byte[] { 0xFE, 0xED, 0xF0, 0x0D },
            };

            using (AsnWriter writer = AsnSerializer.Serialize(bigIntegers, AsnEncodingRules.DER))
            {
                Assert.Equal("300A0202FEEF0204FEEDF00D", writer.EncodeAsSpan().ByteArrayToHex());
            }
        }