public byte[] EncodeX509BasicConstraints2Extension(
            bool certificateAuthority,
            bool hasPathLengthConstraint,
            int pathLengthConstraint)
        {
            //BasicConstraintsSyntax::= SEQUENCE {
            //    cA BOOLEAN DEFAULT FALSE,
            //    pathLenConstraint INTEGER(0..MAX) OPTIONAL,
            //    ... }

            List <byte[][]> segments = new List <byte[][]>(2);

            if (certificateAuthority)
            {
                segments.Add(DerEncoder.SegmentedEncodeBoolean(true));
            }

            if (hasPathLengthConstraint)
            {
                byte[] pathLengthBytes = BitConverter.GetBytes(pathLengthConstraint);
                // Little-Endian => Big-Endian
                Array.Reverse(pathLengthBytes);
                segments.Add(DerEncoder.SegmentedEncodeUnsignedInteger(pathLengthBytes));
            }

            return(DerEncoder.ConstructSequence(segments));
        }
        public byte[] Encode()
        {
            var entries = new List <byte[][]>(Certificates.Count);

            foreach (var essCertIdV2 in Certificates)
            {
                entries.Add(essCertIdV2.Encode());
            }

            return(DerEncoder.ConstructSequence(DerEncoder.ConstructSegmentedSequence(entries)));
        }
示例#3
0
        /// <summary>
        /// Create a signing-certificate-v2 from a certificate.
        /// </summary>
        public static CryptographicAttributeObject GetSigningCertificateV2(IEnumerable <X509Certificate2> chain, Common.HashAlgorithmName hashAlgorithm)
        {
            // Build the cert chain as-is
            var certEntries = chain.Select(e => CreateESSCertIDv2Entry(e, hashAlgorithm)).ToList();

            var data = new AsnEncodedData(Oids.SigningCertificateV2, DerEncoder.ConstructSequence(certEntries));

            // Create an attribute
            return(new CryptographicAttributeObject(
                       oid: new Oid(Oids.SigningCertificateV2),
                       values: new AsnEncodedDataCollection(data)));
        }
        /// <summary>
        /// Allows encoding data that the production helper does not.
        /// </summary>
        private static CryptographicAttributeObject GetCommitmentTypeTestAttribute(params string[] oids)
        {
            var commitmentTypeIndication = new Oid(Oids.CommitmentTypeIndication);
            var values = new AsnEncodedDataCollection();

            foreach (var oid in oids)
            {
                var value = DerEncoder.ConstructSequence(DerEncoder.SegmentedEncodeOid(oid));

                values.Add(new AsnEncodedData(commitmentTypeIndication, value));
            }

            return(new CryptographicAttributeObject(commitmentTypeIndication, values));
        }
        /// <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;

            byte[][] rEncoded = DerEncoder.SegmentedEncodeUnsignedInteger(input.Slice(0, halfLength));
            byte[][] sEncoded = DerEncoder.SegmentedEncodeUnsignedInteger(input.Slice(halfLength, halfLength));

            return(DerEncoder.ConstructSequence(rEncoded, sEncoded));
        }
示例#6
0
        public static void ConstructSequence()
        {
            byte[] expected =
            {
                /* SEQUENCE */ 0x30,     0x07,
                /* INTEGER(0) */ 0x02,   0x01, 0x00,
                /* INTEGER(256) */ 0x02, 0x02, 0x01, 0x00,
            };

            byte[] encoded = DerEncoder.ConstructSequence(
                DerEncoder.SegmentedEncodeUnsignedInteger(new byte[] { 0x00 }),
                DerEncoder.SegmentedEncodeUnsignedInteger(new byte[] { 0x01, 0x00 }));

            Assert.Equal(expected, encoded);
        }
        /// <summary>
        /// Allows encoding bad data that the production helper does not.
        /// </summary>
        private static CryptographicAttributeObject GetCommitmentTypeTestAttribute(params string[] oids)
        {
            var values = new List <byte[][]>();

            foreach (var oid in oids)
            {
                values.Add(DerEncoder.SegmentedEncodeOid(oid));
            }

            var commitmentTypeData = DerEncoder.ConstructSequence(values);
            var data = new AsnEncodedData(Oids.CommitmentTypeIndication, commitmentTypeData);

            // Create an attribute
            return(new CryptographicAttributeObject(
                       oid: new Oid(Oids.CommitmentTypeIndication),
                       values: new AsnEncodedDataCollection(data)));
        }
        public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
        {
            //extKeyUsage EXTENSION ::= {
            //    SYNTAX SEQUENCE SIZE(1..MAX) OF KeyPurposeId
            //    IDENTIFIED BY id - ce - extKeyUsage }
            //
            //KeyPurposeId::= OBJECT IDENTIFIER

            List <byte[][]> segments = new List <byte[][]>(usages.Count);

            foreach (Oid usage in usages)
            {
                segments.Add(DerEncoder.SegmentedEncodeOid(usage));
            }

            return(DerEncoder.ConstructSequence(segments));
        }
        public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
        {
            // The CapiSha1 value is the SHA-1 of the SubjectPublicKeyInfo field, inclusive
            // of the DER structural bytes.

            //SubjectPublicKeyInfo::= SEQUENCE {
            //    algorithm AlgorithmIdentifier{ { SupportedAlgorithms} },
            //    subjectPublicKey BIT STRING,
            //    ... }
            //
            //AlgorithmIdentifier{ ALGORITHM: SupportedAlgorithms} ::= SEQUENCE {
            //    algorithm ALGORITHM.&id({ SupportedAlgorithms}),
            //    parameters ALGORITHM.&Type({ SupportedAlgorithms}
            //    { @algorithm}) OPTIONAL,
            //    ... }
            //
            //ALGORITHM::= CLASS {
            //    &Type OPTIONAL,
            //    &id OBJECT IDENTIFIER UNIQUE }
            //WITH SYNTAX {
            //    [&Type]
            //IDENTIFIED BY &id }

            // key.EncodedKeyValue corresponds to SubjectPublicKeyInfo.subjectPublicKey, except it
            // has had the BIT STRING envelope removed.
            //
            // key.EncodedParameters corresponds to AlgorithmIdentifier.Parameters precisely
            // (DER NULL for RSA, DER Constructed SEQUENCE for DSA)

            byte[]   empty        = Array.Empty <byte>();
            byte[][] algorithmOid = DerEncoder.SegmentedEncodeOid(key.Oid);
            // Because ConstructSegmentedSequence doesn't look to see that it really is tag+length+value (but does check
            // that the array has length 3), just hide the joined TLV triplet in the last element.
            byte[][] segmentedParameters = { empty, empty, key.EncodedParameters.RawData };
            byte[][] algorithmIdentifier = DerEncoder.ConstructSegmentedSequence(algorithmOid, segmentedParameters);
            byte[][] subjectPublicKey    = DerEncoder.SegmentedEncodeBitString(key.EncodedKeyValue.RawData);

            using (SHA1 hash = SHA1.Create())
            {
                return(hash.ComputeHash(
                           DerEncoder.ConstructSequence(
                               algorithmIdentifier,
                               subjectPublicKey)));
            }
        }
示例#10
0
        internal static byte[] X500DistinguishedNameEncode(
            string stringForm,
            X500DistinguishedNameFlags flags)
        {
            bool reverse  = (flags & X500DistinguishedNameFlags.Reversed) == X500DistinguishedNameFlags.Reversed;
            bool noQuotes = (flags & X500DistinguishedNameFlags.DoNotUseQuotes) == X500DistinguishedNameFlags.DoNotUseQuotes;

            List <char> dnSeparators;

            // This rank ordering is based off of testing against the Windows implementation.
            if ((flags & X500DistinguishedNameFlags.UseSemicolons) == X500DistinguishedNameFlags.UseSemicolons)
            {
                // Just semicolon.
                dnSeparators = s_useSemicolonSeparators;
            }
            else if ((flags & X500DistinguishedNameFlags.UseCommas) == X500DistinguishedNameFlags.UseCommas)
            {
                // Just comma
                dnSeparators = s_useCommaSeparators;
            }
            else if ((flags & X500DistinguishedNameFlags.UseNewLines) == X500DistinguishedNameFlags.UseNewLines)
            {
                // CR or LF.  Not "and".  Whichever is first was the separator, the later one is trimmed as whitespace.
                dnSeparators = s_useNewlineSeparators;
            }
            else
            {
                // Comma or semicolon, but not CR or LF.
                dnSeparators = s_defaultSeparators;
            }

            Debug.Assert(dnSeparators.Count != 0);

            List <byte[][]> encodedSets = ParseDistinguishedName(stringForm, dnSeparators, noQuotes);

            if (reverse)
            {
                encodedSets.Reverse();
            }

            return(DerEncoder.ConstructSequence(encodedSets));
        }
        public void GetRepositoryCountersignature_WithRepositoryCountersignatureWithInvalidPackageOwners_Throws()
        {
            using (var test = new Test(_fixture))
            {
                test.CreateValidAuthorPrimarySignature();

                // Generate countersignature
                test.CounterCmsSigner.SignedAttributes.Add(
                    AttributeUtility.CreateCommitmentTypeIndication(SignatureType.Repository));

                var invalidPackageOwnersBytes = DerEncoder.ConstructSequence(
                    (new List <string> {
                    "", "   "
                }).Select(packageOwner => DerEncoder.SegmentedEncodeUtf8String(packageOwner.ToCharArray())));

                var invalidPackageOwners = new System.Security.Cryptography.CryptographicAttributeObject(
                    new System.Security.Cryptography.Oid(Oids.NuGetPackageOwners),
                    new System.Security.Cryptography.AsnEncodedDataCollection(new System.Security.Cryptography.AsnEncodedData(Oids.NuGetPackageOwners, invalidPackageOwnersBytes)));

                test.CounterCmsSigner.SignedAttributes.Add(
                    invalidPackageOwners);
                test.CounterCmsSigner.SignedAttributes.Add(
                    AttributeUtility.CreateNuGetV3ServiceIndexUrl(new Uri("https://api.nuget.org/v3/index.json")));
                test.CounterCmsSigner.SignedAttributes.Add(
                    new Pkcs9SigningTime());
                test.CounterCmsSigner.SignedAttributes.Add(
                    AttributeUtility.CreateSigningCertificateV2(test.Certificate, HashAlgorithmName.SHA256));

                // Create counter signature
                test.PrimarySignedCms.SignerInfos[0].ComputeCounterSignature(test.CounterCmsSigner);

                // Load primary signature
                var primarySignature = PrimarySignature.Load(test.PrimarySignedCms.Encode());

                // Validate countersignature
                var exception = Assert.Throws <SignatureException>(
                    () => RepositoryCountersignature.GetRepositoryCountersignature(primarySignature));

                Assert.Equal(NuGetLogCode.NU3000, exception.Code);
                Assert.Equal("The nuget-package-owners attribute is invalid.", exception.Message);
            }
        }
示例#12
0
        /// <summary>
        /// Create a CommitmentTypeIndication attribute.
        /// https://tools.ietf.org/html/rfc5126.html#section-5.11.1
        /// </summary>
        public static CryptographicAttributeObject GetCommitmentTypeIndication(SignatureType type)
        {
            // SignatureType -> Oid
            var valueOid = GetSignatureTypeOid(type);

            // DER encode the signature type Oid in a sequence.
            // CommitmentTypeQualifier ::= SEQUENCE {
            // commitmentTypeIdentifier CommitmentTypeIdentifier,
            // qualifier                  ANY DEFINED BY commitmentTypeIdentifier }
            var commitmentTypeData = DerEncoder.ConstructSequence(new List <byte[][]>()
            {
                DerEncoder.SegmentedEncodeOid(valueOid)
            });
            var data = new AsnEncodedData(Oids.CommitmentTypeIndication, commitmentTypeData);

            // Create an attribute
            return(new CryptographicAttributeObject(
                       oid: new Oid(Oids.CommitmentTypeIndication),
                       values: new AsnEncodedDataCollection(data)));
        }
        public static byte[] ConvertIeee1363ToDer(byte[] input)
        {
            int num = input.Length / 2;

            return(DerEncoder.ConstructSequence(DerEncoder.SegmentedEncodeUnsignedInteger(input, 0, num), DerEncoder.SegmentedEncodeUnsignedInteger(input, num, num)));
        }
 internal byte[] Encode()
 {
     return(DerEncoder.ConstructSequence(DerEncoder.SegmentedEncodeOid(CommitmentTypeIdentifier)));
 }
 public byte[] Encode()
 {
     return(DerEncoder.ConstructSequence(
                PackageOwners.Select(packageOwner => DerEncoder.SegmentedEncodeUtf8String(packageOwner.ToCharArray()))));
 }