Exemple #1
0
        private byte[] GetKeyIdentifier(Mono.Security.X509.X509Certificate x509)
        {
            // if present in certificate return value of the SubjectKeyIdentifier
            Mono.Security.X509.X509Extension extn = x509.Extensions ["2.5.29.14"];
            if (extn != null)
            {
                ASN1 bs = new ASN1(extn.Value.Value);
                return(bs.Value);
            }
            // strangely DEPRECATED keyAttributes isn't used here (like KeyUsage)

            // if not then we must calculate the SubjectKeyIdentifier ourselve
            // Note: MS does that hash on the complete subjectPublicKeyInfo (unlike PKIX)
            // http://groups.google.ca/groups?selm=e7RqM%24plCHA.1488%40tkmsftngp02&oe=UTF-8&output=gplain
            ASN1 subjectPublicKeyInfo = new ASN1(0x30);
            ASN1 algo = subjectPublicKeyInfo.Add(new ASN1(0x30));

            algo.Add(new ASN1(CryptoConfig.EncodeOID(x509.KeyAlgorithm)));
            // FIXME: does it work for DSA certs (without an 2.5.29.14 extension ?)
            algo.Add(new ASN1(x509.KeyAlgorithmParameters));
            byte[] pubkey  = x509.PublicKey;
            byte[] bsvalue = new byte [pubkey.Length + 1];             // add unused bits (0) before the public key
            Array.Copy(pubkey, 0, bsvalue, 1, pubkey.Length);
            subjectPublicKeyInfo.Add(new ASN1(0x03, bsvalue));
            SHA1 sha = SHA1.Create();

            return(sha.ComputeHash(subjectPublicKeyInfo.GetBytes()));
        }
Exemple #2
0
        public static void EncodeOID_Compat()
        {
#pragma warning disable SYSLIB0031            // EncodeOID is obsolete
            string actual = CryptoConfig.EncodeOID("-1.2.-3").ByteArrayToHex();
            Assert.Equal("0602DAFD", actual); // Negative values not checked
#pragma warning restore SYSLIB0031
        }
Exemple #3
0
    public static bool Test()
    {
        bool bRes = true;

        byte[][] abEnc = new byte[2][];
        abEnc[0] = new byte[5] {
            0x06, 0x03, 0x55, 0x04, 0x03
        };
        abEnc[1] = new byte[7] {
            0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A
        };
        string[] sOID = new string[2] {
            "2.5.4.3", "1.3.14.3.2.26"
        };

        for (int i = 0; i < 2; i++)
        {
            byte[] abTmpEnc = CryptoConfig.EncodeOID(sOID[i]);
            Console.WriteLine("Encoding calculated for OID " + sOID[i] + " is");
            PrintByteArray(abTmpEnc);
            if (!Compare(abEnc[i], abTmpEnc))
            {
                Console.WriteLine("WRONG result for OID " + sOID[i] + ", expected");
                PrintByteArray(abEnc[i]);
                bRes = false;
            }
        }


        return(bRes);
    }
 public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
 {
     if (rgbHash == null)
     {
         throw new ArgumentNullException(nameof(rgbHash));
     }
     if (rgbSignature == null)
     {
         throw new ArgumentNullException(nameof(rgbSignature));
     }
     if (_strOID == null)
     {
         throw new CryptographicUnexpectedOperationException("Cryptography_MissingOID");
     }
     if (_rsaKey == null)
     {
         throw new CryptographicUnexpectedOperationException("Cryptography_MissingKey");
     }
     if (_rsaKey is RSACryptoServiceProvider)
     {
         throw new Exception("Unexpected path");
         //int algIdFromOid = GetAlgIdFromOid(_strOID, OidGroup.HashAlgorithm);
         //return ((RSACryptoServiceProvider)_rsaKey).VerifyHash(rgbHash, algIdFromOid, rgbSignature);
     }
     if (OverridesVerifyHash)
     {
         HashAlgorithmName hashAlgorithmName = OidToHashAlgorithmName(_strOID);
         return(_rsaKey.VerifyHash(rgbHash, rgbSignature, hashAlgorithmName, RSASignaturePadding.Pkcs1));
     }
     byte[] rhs = RsaPkcs1Padding(_rsaKey, CryptoConfig.EncodeOID(_strOID), rgbHash);
     return(CompareBigIntArrays(_rsaKey.EncryptValue(rgbSignature), rhs));
 }
Exemple #5
0
 public void EncodeOID_InvalidSecondPart()
 {
     // invalid OID - second value < 40 for 0. and 1. (modulo 40)
     // however it works with MS BCL
     byte[] tooBigSecondPartOID = CryptoConfig.EncodeOID("0.40");
     byte[] tooBigSecondPartRes = { 0x06, 0x01, 0x28 };
     Assert.AreEqual(tooBigSecondPartRes, tooBigSecondPartOID, "OID: 0.40");
 }
 public static ASN1 FromOid(string oid)
 {
     if (oid == null)
     {
         throw new ArgumentNullException("oid");
     }
     return(new ASN1(CryptoConfig.EncodeOID(oid)));
 }
Exemple #7
0
 public static void EncodeOID_Validation()
 {
     Assert.Throws <ArgumentNullException>(() => CryptoConfig.EncodeOID(null));
     Assert.Throws <FormatException>(() => CryptoConfig.EncodeOID(string.Empty));
     Assert.Throws <FormatException>(() => CryptoConfig.EncodeOID("BAD.OID"));
     Assert.Throws <FormatException>(() => CryptoConfig.EncodeOID("1.2.BAD.OID"));
     Assert.Throws <OverflowException>(() => CryptoConfig.EncodeOID("1." + uint.MaxValue));
 }
Exemple #8
0
 public static void EncodeOID_Value_Boundary_And_Compat(uint elementValue, string expectedEncoding)
 {
     // Boundary cases in EncodeOID; output may produce the wrong value mathematically due to encoding
     // algorithm semantics but included here for compat reasons.
     byte[] actual   = CryptoConfig.EncodeOID("1." + elementValue.ToString());
     byte[] expected = expectedEncoding.HexToByteArray();
     Assert.Equal(expected, actual);
 }
Exemple #9
0
 public void EncodeOID_InvalidStart()
 {
     // invalid OID - must start with 0, 1 or 2
     // however it works with MS BCL
     byte[] oid3 = CryptoConfig.EncodeOID("3.0");
     byte[] res3 = { 0x06, 0x01, 0x78 };
     Assert.AreEqual(res3, oid3, "OID: 3.0");
 }
Exemple #10
0
 public void EncodeOID()
 {
     // OID starts with 0, 1 or 2
     Assert.AreEqual(oidETSI, CryptoConfig.EncodeOID("0.4.0.0"), "OID starting with 0.");
     Assert.AreEqual(oidSHA1, CryptoConfig.EncodeOID("1.3.14.3.2.26"), "OID starting with 1.");
     Assert.AreEqual(oidASN1CharacterModule, CryptoConfig.EncodeOID("2.1.0.0.0"), "OID starting with 2.");
     // OID numbers can span multiple bytes
     Assert.AreEqual(oidmd5withRSAEncryption, CryptoConfig.EncodeOID("1.2.840.113549.1.1.4"), "OID with numbers spanning multiple bytes");
 }
Exemple #11
0
        public static void EncodeOID_Validation()
        {
#pragma warning disable SYSLIB0031 // EncodeOID is obsolete
            Assert.Throws <ArgumentNullException>(() => CryptoConfig.EncodeOID(null));
            Assert.Throws <FormatException>(() => CryptoConfig.EncodeOID(string.Empty));
            Assert.Throws <FormatException>(() => CryptoConfig.EncodeOID("BAD.OID"));
            Assert.Throws <FormatException>(() => CryptoConfig.EncodeOID("1.2.BAD.OID"));
            Assert.Throws <OverflowException>(() => CryptoConfig.EncodeOID("1." + uint.MaxValue));
#pragma warning restore SYSLIB0031
        }
Exemple #12
0
        public static void MapAndEncodeOID(string alg, string expectedOid, string expectedEncoding)
        {
            string oid = CryptoConfig.MapNameToOID(alg);

            Assert.Equal(expectedOid, oid);

            byte[] actual   = CryptoConfig.EncodeOID(oid);
            byte[] expected = expectedEncoding.HexToByteArray();
            Assert.Equal(expected, actual);
        }
    static void Main(string[] args)
    {
        // Create a CryptoConfig object to store configuration information.
        //<Snippet2>
        CryptoConfig cryptoConfig = new CryptoConfig();
        //</Snippet2>

        // Retrieve the class path for CryptoConfig.
        //<Snippet7>
        string classDescription = cryptoConfig.ToString();
        //</Snippet7>

        // Create a new SHA1 provider.
        //<Snippet4>
        SHA1CryptoServiceProvider SHA1alg =
            (SHA1CryptoServiceProvider)CryptoConfig.CreateFromName("SHA1");
        //</Snippet4>

        // Create an RSAParameters with the TestContainer key container.
        //<Snippet5>
        CspParameters parameters = new CspParameters();

        parameters.KeyContainerName = "TestContainer";
        Object[] argsArray = new Object[] { parameters };

        // Instantiate the RSA provider instance accessing the TestContainer
        // key container.
        RSA rsa = (RSA)
                  CryptoConfig.CreateFromName("RSA", argsArray);
        //</Snippet5>

        // Use the MapNameToOID method to get an object identifier
        // (OID) from the string name of the SHA1 algorithm.
        //<Snippet3>
        string sha1Oid = CryptoConfig.MapNameToOID("SHA1");

        //</Snippet3>

        // Encode the specified object identifier.
        //<Snippet6>
        byte[] encodedMessage = CryptoConfig.EncodeOID(sha1Oid);
        //</Snippet6>

        // Display the results to the console.
        Console.WriteLine("** " + classDescription + " **");
        Console.WriteLine("Created an RSA provider " +
                          "with a KeyContainerName called " + parameters.KeyContainerName +
                          ".");
        Console.WriteLine("Object identifier from the SHA1 name:" + sha1Oid);
        Console.WriteLine("The object identifier encoded: " +
                          System.Text.Encoding.ASCII.GetString(encodedMessage));
        Console.WriteLine("This sample completed successfully; " +
                          "press Enter to exit.");
        Console.ReadLine();
    }
Exemple #14
0
        public static void MapAndEncodeOID(string alg, string expectedOid, string expectedEncoding)
        {
#pragma warning disable SYSLIB0031 // EncodeOID is obsolete
            string oid = CryptoConfig.MapNameToOID(alg);
            Assert.Equal(expectedOid, oid);

            byte[] actual   = CryptoConfig.EncodeOID(oid);
            byte[] expected = expectedEncoding.HexToByteArray();
            Assert.Equal(expected, actual);
#pragma warning restore SYSLIB0031
        }
Exemple #15
0
 /// <summary>
 /// Encodes an instance of <see cref="Oid"/> class to a ASN.1-encoded byte array that represents <strong>OBJECT IDENTIFIER</strong> type.
 /// </summary>
 /// <param name="oid">An instance of <see cref="Oid"/> class.</param>
 /// <exception cref="ArgumentNullException"><strong>oid</strong> parameter is null reference.</exception>
 /// <exception cref="ArgumentException">The object identifier is not initialized.</exception>
 /// <returns>ASN.1-encoded byte array.</returns>
 public static Byte[] EncodeObjectIdentifier(Oid oid)
 {
     if (oid == null)
     {
         throw new ArgumentNullException();
     }
     if (String.IsNullOrEmpty(oid.Value))
     {
         throw new ArgumentException("oid");
     }
     return(CryptoConfig.EncodeOID(oid.Value));
 }
        public static byte[] ExportPublicKeyInDERFormat(this X509Certificate certificate)
        {
            byte[] algOid = CryptoConfig.EncodeOID(certificate.GetKeyAlgorithm());

            byte[] algParams = certificate.GetKeyAlgorithmParameters();

            byte[] algId = BuildSimpleDERSequence(algOid, algParams);

            byte[] publicKey = WrapAsBitString(certificate.GetPublicKey());

            return(BuildSimpleDERSequence(algId, publicKey));
        }
Exemple #17
0
        // PKCS #1 v.2.1, Section 9.2
        // EMSA-PKCS1-v1_5-Encode
        public static byte[] Encode_v15(HashAlgorithm hash, byte[] hashValue, int emLength)
        {
            if (hashValue.Length != (hash.HashSize >> 3))
            {
                throw new CryptographicException("bad hash length for " + hash.ToString());
            }

            // DigestInfo ::= SEQUENCE {
            //	digestAlgorithm AlgorithmIdentifier,
            //	digest OCTET STRING
            // }

            byte[] t = null;

            string oid = CryptoConfig.MapNameToOID(hash.ToString());

            if (oid != null)
            {
                ASN1 digestAlgorithm = new ASN1(0x30);
                digestAlgorithm.Add(new ASN1(CryptoConfig.EncodeOID(oid)));
                digestAlgorithm.Add(new ASN1(0x05));                            // NULL
                ASN1 digest     = new ASN1(0x04, hashValue);
                ASN1 digestInfo = new ASN1(0x30);
                digestInfo.Add(digestAlgorithm);
                digestInfo.Add(digest);

                t = digestInfo.GetBytes();
            }
            else
            {
                // There are no valid OID, in this case t = hashValue
                // This is the case of the MD5SHA hash algorithm
                t = hashValue;
            }

            Buffer.BlockCopy(hashValue, 0, t, t.Length - hashValue.Length, hashValue.Length);

            int PSLength = System.Math.Max(8, emLength - t.Length - 3);

            // PS = PSLength of 0xff

            // EM = 0x00 | 0x01 | PS | 0x00 | T
            byte[] EM = new byte [PSLength + t.Length + 3];
            EM [1] = 0x01;
            for (int i = 2; i < PSLength + 2; i++)
            {
                EM[i] = 0xff;
            }
            Buffer.BlockCopy(t, 0, EM, PSLength + 3, t.Length);

            return(EM);
        }
Exemple #18
0
        // LAMESPEC: OID greater that 0x7F (127) bytes aren't supported by the MS Framework
        public void EncodeOID_BiggerThan127bytes()
        {
            // "ms"-invalid OID - greater than 127 bytes (length encoding)
            // OID longer than 127 bytes (so length must be encoded on multiple bytes)
            string baseOID  = "1.3.6.1.4.1.11071.0.";
            string lastPart = "1111111111";     // must fit in int32

            for (int i = 1; i < 30; i++)
            {
                baseOID += lastPart + ".";
            }
            baseOID += "0";
            byte[] tooLongOID = CryptoConfig.EncodeOID(baseOID);
        }
        private bool VerifyHash(byte[] signature, byte[] rgbHash)
        {
            string oid = CryptoConfig.MapNameToOID("SHA1");

            if (this._key is RSACryptoServiceProvider)
            {
                return(((RSACryptoServiceProvider)this._key).VerifyHash(rgbHash, oid, signature));
            }
            if (this._key is RSACryptoServiceProvider)
            {
                return(((RSACryptoServiceProvider)this._key).VerifyHash(rgbHash, oid, signature));
            }
            int keySizeBytes = this._key.KeySize / 8;

            byte[] keyBuffer = new byte[keySizeBytes];
            byte[] oidBuffer = CryptoConfig.EncodeOID(oid);
            int    oidLength = oidBuffer.Length;

            byte[] encBuffer = new byte[(oidLength + 8) + rgbHash.Length];
            encBuffer[0] = 0x30;
            int totalSize = encBuffer.Length - 2;

            encBuffer[1] = (byte)totalSize;
            encBuffer[2] = 0x30;
            totalSize    = oidBuffer.Length + 2;
            encBuffer[3] = (byte)totalSize;
            Buffer.BlockCopy(oidBuffer, 0, encBuffer, 4, oidLength);
            encBuffer[4 + oidLength]       = 5;
            encBuffer[(4 + oidLength) + 1] = 0;
            encBuffer[(4 + oidLength) + 2] = 4;
            encBuffer[(4 + oidLength) + 3] = (byte)rgbHash.Length;
            Buffer.BlockCopy(rgbHash, 0, encBuffer, oidLength + 8, rgbHash.Length);
            int cboid = (keySizeBytes - rgbHash.Length) - encBuffer.Length;

            if (cboid <= 2)
            {
                throw new CryptographicUnexpectedOperationException("Cryptography_InvalidOID");
            }
            keyBuffer[0] = 0;
            keyBuffer[1] = 1;
            for (int i = 2; i < (cboid - 1); i++)
            {
                keyBuffer[i] = 0xff;
            }
            keyBuffer[cboid - 1] = 0;
            Buffer.BlockCopy(encBuffer, 0, keyBuffer, cboid, encBuffer.Length);
            Buffer.BlockCopy(rgbHash, 0, keyBuffer, cboid + encBuffer.Length, rgbHash.Length);
            byte[] encryptedValue = this._key.EncryptValue(signature);
            return(encryptedValue.Equals(keyBuffer));
        }
        private byte[] SignHash(byte[] rgbHash)
        {
            string oid = CryptoConfig.MapNameToOID("SHA1");

            if (this._key is System.Security.Cryptography.RSACryptoServiceProvider)
            {
                return(((System.Security.Cryptography.RSACryptoServiceProvider) this._key).SignHash(rgbHash, oid));
            }
            if (this._key is System.Security.Cryptography.RSACryptoServiceProvider)
            {
                return(((System.Security.Cryptography.RSACryptoServiceProvider) this._key).SignHash(rgbHash, oid));
            }
            int keySizeBytes = this._key.KeySize / 8;

            byte[] keyBuffer = new byte[keySizeBytes];
            byte[] oidBuffer = CryptoConfig.EncodeOID(oid);
            int    oidLength = oidBuffer.Length;

            byte[] encBuffer = new byte[(oidLength + 8) + rgbHash.Length];
            encBuffer[0] = 0x30;
            int num5 = encBuffer.Length - 2;

            encBuffer[1] = (byte)num5;
            encBuffer[2] = 0x30;
            num5         = oidBuffer.Length + 2;
            encBuffer[3] = (byte)num5;
            Buffer.BlockCopy(oidBuffer, 0, encBuffer, 4, oidLength);
            encBuffer[4 + oidLength]       = 5;
            encBuffer[(4 + oidLength) + 1] = 0;
            encBuffer[(4 + oidLength) + 2] = 4;
            encBuffer[(4 + oidLength) + 3] = (byte)rgbHash.Length;
            Buffer.BlockCopy(rgbHash, 0, encBuffer, oidLength + 8, rgbHash.Length);
            int cboid = (keySizeBytes - rgbHash.Length) - encBuffer.Length;

            if (cboid <= 2)
            {
                throw new CryptographicUnexpectedOperationException("Cryptography_InvalidOID");
            }
            keyBuffer[0] = 0;
            keyBuffer[1] = 1;
            for (int num3 = 2; num3 < (cboid - 1); num3++)
            {
                keyBuffer[num3] = 0xff;
            }
            keyBuffer[cboid - 1] = 0;
            Buffer.BlockCopy(encBuffer, 0, keyBuffer, cboid, encBuffer.Length);
            Buffer.BlockCopy(rgbHash, 0, keyBuffer, cboid + encBuffer.Length, rgbHash.Length);
            return(this._key.DecryptValue(keyBuffer));
        }
Exemple #21
0
        public static void EncodeOID_Length_Boundary()
        {
            string valueToRepeat = "1.1";

            // Build a string like 1.11.11.11. ... .11.1, which has 0x80 separators.
            // The BER/DER encoding of an OID has a minimum number of bytes as the number of separator characters,
            // so this would produce an OID with a length segment of more than one byte, which EncodeOID can't handle.
            string s = new StringBuilder(valueToRepeat.Length * 0x80).Insert(0, valueToRepeat, 0x80).ToString();

            Assert.Throws <CryptographicUnexpectedOperationException>(() => CryptoConfig.EncodeOID(s));

            // Try again with one less separator for the boundary case, but the particular output is really long
            // and would just clutter up this test, so only verify it doesn't throw.
            s = new StringBuilder(valueToRepeat.Length * 0x7f).Insert(0, valueToRepeat, 0x7f).ToString();
            CryptoConfig.EncodeOID(s);
        }
        public X509SubjectKeyIdentifierExtension(PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            byte[] pkraw = key.EncodedKeyValue.RawData;
            // compute SKI
            switch (algorithm)
            {
            // hash of the public key, excluding Tag, Length and unused bits values
            case X509SubjectKeyIdentifierHashAlgorithm.Sha1:
                _subjectKeyIdentifier = SHA1.Create().ComputeHash(pkraw);
                break;

            // 0100 bit pattern followed by the 60 last bit of the hash
            case X509SubjectKeyIdentifierHashAlgorithm.ShortSha1:
                byte[] hash = SHA1.Create().ComputeHash(pkraw);
                _subjectKeyIdentifier = new byte [8];
                Buffer.BlockCopy(hash, 12, _subjectKeyIdentifier, 0, 8);
                _subjectKeyIdentifier [0] = (byte)(0x40 | (_subjectKeyIdentifier [0] & 0x0F));
                break;

            // hash of the public key, including Tag, Length and unused bits values
            case X509SubjectKeyIdentifierHashAlgorithm.CapiSha1:
                // CryptoAPI does that hash on the complete subjectPublicKeyInfo (unlike PKIX)
                // http://groups.google.ca/groups?selm=e7RqM%24plCHA.1488%40tkmsftngp02&oe=UTF-8&output=gplain
                ASN1 subjectPublicKeyInfo = new ASN1(0x30);
                ASN1 algo = subjectPublicKeyInfo.Add(new ASN1(0x30));
                algo.Add(new ASN1(CryptoConfig.EncodeOID(key.Oid.Value)));
                algo.Add(new ASN1(key.EncodedParameters.RawData));
                // add an extra byte for the unused bits (none)
                byte[] full = new byte [pkraw.Length + 1];
                Buffer.BlockCopy(pkraw, 0, full, 1, pkraw.Length);
                subjectPublicKeyInfo.Add(new ASN1(0x03, full));
                _subjectKeyIdentifier = SHA1.Create().ComputeHash(subjectPublicKeyInfo.GetBytes());
                break;

            default:
                throw new ArgumentException("algorithm");
            }

            _oid          = new Oid(oid, friendlyName);
            base.Critical = critical;
            RawData       = Encode();
        }
        /// <summary>Initializes a new instance of the <see cref="T:System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension" /> class using a public key, a hash algorithm identifier, and a value indicating whether the extension is critical. </summary>
        /// <param name="key">A <see cref="T:System.Security.Cryptography.X509Certificates.PublicKey" /> object to create a subject key identifier (SKI) from.</param>
        /// <param name="algorithm">One of the <see cref="T:System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm" /> values that identifies which hash algorithm to use.</param>
        /// <param name="critical">true if the extension is critical; otherwise, false.</param>
        public X509SubjectKeyIdentifierExtension(PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            byte[] rawData = key.EncodedKeyValue.RawData;
            switch (algorithm)
            {
            case X509SubjectKeyIdentifierHashAlgorithm.Sha1:
                this._subjectKeyIdentifier = SHA1.Create().ComputeHash(rawData);
                break;

            case X509SubjectKeyIdentifierHashAlgorithm.ShortSha1:
            {
                byte[] src = SHA1.Create().ComputeHash(rawData);
                this._subjectKeyIdentifier = new byte[8];
                Buffer.BlockCopy(src, 12, this._subjectKeyIdentifier, 0, 8);
                this._subjectKeyIdentifier[0] = (64 | (this._subjectKeyIdentifier[0] & 15));
                break;
            }

            case X509SubjectKeyIdentifierHashAlgorithm.CapiSha1:
            {
                ASN1 asn  = new ASN1(48);
                ASN1 asn2 = asn.Add(new ASN1(48));
                asn2.Add(new ASN1(CryptoConfig.EncodeOID(key.Oid.Value)));
                asn2.Add(new ASN1(key.EncodedParameters.RawData));
                byte[] array = new byte[rawData.Length + 1];
                Buffer.BlockCopy(rawData, 0, array, 1, rawData.Length);
                asn.Add(new ASN1(3, array));
                this._subjectKeyIdentifier = SHA1.Create().ComputeHash(asn.GetBytes());
                break;
            }

            default:
                throw new ArgumentException("algorithm");
            }
            this._oid     = new Oid("2.5.29.14", "Subject Key Identifier");
            base.Critical = critical;
            base.RawData  = this.Encode();
        }
Exemple #24
0
        public static void EncodeOID_Compat()
        {
            string actual = CryptoConfig.EncodeOID("-1.2.-3").ByteArrayToHex();

            Assert.Equal("0602DAFD", actual); // Negative values not checked
        }
        public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
        {
            if (findValue == null)
            {
                throw new ArgumentNullException("findValue");
            }
            string            text              = string.Empty;
            string            text2             = string.Empty;
            X509KeyUsageFlags x509KeyUsageFlags = X509KeyUsageFlags.None;
            DateTime          t = DateTime.MinValue;

            switch (findType)
            {
            case X509FindType.FindByThumbprint:
            case X509FindType.FindBySubjectName:
            case X509FindType.FindBySubjectDistinguishedName:
            case X509FindType.FindByIssuerName:
            case X509FindType.FindByIssuerDistinguishedName:
            case X509FindType.FindBySerialNumber:
            case X509FindType.FindByTemplateName:
            case X509FindType.FindBySubjectKeyIdentifier:
                try
                {
                    text = (string)findValue;
                }
                catch (Exception inner)
                {
                    string text3 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "string"
                    });
                    throw new CryptographicException(text3, inner);
                }
                break;

            case X509FindType.FindByTimeValid:
            case X509FindType.FindByTimeNotYetValid:
            case X509FindType.FindByTimeExpired:
                try
                {
                    t = (DateTime)findValue;
                }
                catch (Exception inner2)
                {
                    string text4 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509DateTime"
                    });
                    throw new CryptographicException(text4, inner2);
                }
                break;

            case X509FindType.FindByApplicationPolicy:
            case X509FindType.FindByCertificatePolicy:
            case X509FindType.FindByExtension:
                try
                {
                    text2 = (string)findValue;
                }
                catch (Exception inner3)
                {
                    string text5 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509KeyUsageFlags"
                    });
                    throw new CryptographicException(text5, inner3);
                }
                try
                {
                    CryptoConfig.EncodeOID(text2);
                }
                catch (CryptographicUnexpectedOperationException)
                {
                    string text6 = Locale.GetText("Invalid OID value '{0}'.", new object[]
                    {
                        text2
                    });
                    throw new ArgumentException("findValue", text6);
                }
                break;

            case X509FindType.FindByKeyUsage:
                try
                {
                    x509KeyUsageFlags = (X509KeyUsageFlags)((int)findValue);
                }
                catch (Exception inner4)
                {
                    string text7 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509KeyUsageFlags"
                    });
                    throw new CryptographicException(text7, inner4);
                }
                break;

            default:
            {
                string text8 = Locale.GetText("Invalid find type '{0}'.", new object[]
                    {
                        findType
                    });
                throw new CryptographicException(text8);
            }
            }
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;
            X509Certificate2Collection x509Certificate2Collection = new X509Certificate2Collection();

            foreach (object obj in base.InnerList)
            {
                X509Certificate2 x509Certificate = (X509Certificate2)obj;
                bool             flag            = false;
                switch (findType)
                {
                case X509FindType.FindByThumbprint:
                    flag = (string.Compare(text, x509Certificate.Thumbprint, true, invariantCulture) == 0 || string.Compare(text, x509Certificate.GetCertHashString(), true, invariantCulture) == 0);
                    break;

                case X509FindType.FindBySubjectName:
                {
                    string nameInfo = x509Certificate.GetNameInfo(X509NameType.SimpleName, false);
                    flag = (nameInfo.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    break;
                }

                case X509FindType.FindBySubjectDistinguishedName:
                    flag = (string.Compare(text, x509Certificate.Subject, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindByIssuerName:
                {
                    string nameInfo2 = x509Certificate.GetNameInfo(X509NameType.SimpleName, true);
                    flag = (nameInfo2.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    break;
                }

                case X509FindType.FindByIssuerDistinguishedName:
                    flag = (string.Compare(text, x509Certificate.Issuer, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindBySerialNumber:
                    flag = (string.Compare(text, x509Certificate.SerialNumber, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindByTimeValid:
                    flag = (t >= x509Certificate.NotBefore && t <= x509Certificate.NotAfter);
                    break;

                case X509FindType.FindByTimeNotYetValid:
                    flag = (t < x509Certificate.NotBefore);
                    break;

                case X509FindType.FindByTimeExpired:
                    flag = (t > x509Certificate.NotAfter);
                    break;

                case X509FindType.FindByApplicationPolicy:
                    flag = (x509Certificate.Extensions.Count == 0);
                    break;

                case X509FindType.FindByExtension:
                    flag = (x509Certificate.Extensions[text2] != null);
                    break;

                case X509FindType.FindByKeyUsage:
                {
                    X509KeyUsageExtension x509KeyUsageExtension = x509Certificate.Extensions["2.5.29.15"] as X509KeyUsageExtension;
                    flag = (x509KeyUsageExtension == null || (x509KeyUsageExtension.KeyUsages & x509KeyUsageFlags) == x509KeyUsageFlags);
                    break;
                }

                case X509FindType.FindBySubjectKeyIdentifier:
                {
                    X509SubjectKeyIdentifierExtension x509SubjectKeyIdentifierExtension = x509Certificate.Extensions["2.5.29.14"] as X509SubjectKeyIdentifierExtension;
                    if (x509SubjectKeyIdentifierExtension != null)
                    {
                        flag = (string.Compare(text, x509SubjectKeyIdentifierExtension.SubjectKeyIdentifier, true, invariantCulture) == 0);
                    }
                    break;
                }
                }
                if (flag)
                {
                    if (validOnly)
                    {
                        try
                        {
                            if (x509Certificate.Verify())
                            {
                                x509Certificate2Collection.Add(x509Certificate);
                            }
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        x509Certificate2Collection.Add(x509Certificate);
                    }
                }
            }
            return(x509Certificate2Collection);
        }
Exemple #26
0
    // Construct an invalid DSACryptoServiceProvider to throw a
    // CryptographicUnexpectedOperationException for introspection.
    private void ShowProperties()
    {
        // Attempting to encode an OID greater than 127 bytes is not supported
        // and will throw an exception.
        string veryLongNumber = "1234567890.1234567890.";

        for (int i = 0; i < 4; i++)
        {
            veryLongNumber += veryLongNumber;
        }
        veryLongNumber += "0";
        try
        {
            byte[] tooLongOID = CryptoConfig.EncodeOID(veryLongNumber);
        }
        catch (CryptographicUnexpectedOperationException ex)
        {
            // Retrieve the link to the Help file for the exception.
            //<Snippet6>
            string helpLink = ex.HelpLink;
            //</Snippet6>

            // Retrieve the exception that caused the current
            // CryptographicUnexpectedOperationException.
            //<Snippet7>
            System.Exception innerException = ex.InnerException;
            //</Snippet7>
            string innerExceptionMessage = "";
            if (innerException != null)
            {
                innerExceptionMessage = innerException.ToString();
            }

            // Retrieve the message that describes the exception.
            //<Snippet8>
            string message = ex.Message;
            //</Snippet8>

            // Retrieve the name of the application that caused the exception.
            //<Snippet9>
            string exceptionSource = ex.Source;
            //</Snippet9>

            // Retrieve the call stack at the time the exception occurred.
            //<Snippet10>
            string stackTrace = ex.StackTrace;
            //</Snippet10>

            // Retrieve the method that threw the exception.
            //<Snippet11>
            System.Reflection.MethodBase targetSite = ex.TargetSite;
            //</Snippet11>
            string siteName = targetSite.Name;

            // Retrieve the entire exception as a single string.
            //<Snippet12>
            string entireException = ex.ToString();
            //</Snippet12>

            // GetObjectData
            setSerializationInfo(ref ex);

            // Get the root exception that caused the current
            // CryptographicUnexpectedOperationException.
            //<Snippet13>
            System.Exception baseException = ex.GetBaseException();
            //</Snippet13>
            string baseExceptionMessage = "";
            if (baseException != null)
            {
                baseExceptionMessage = baseException.Message;
            }

            Console.WriteLine("Caught an expected exception:");
            Console.WriteLine(entireException + "\n");

            Console.WriteLine("Properties of the exception are as follows:");
            Console.WriteLine("Message: " + message);
            Console.WriteLine("Source: " + exceptionSource);
            Console.WriteLine("Stack trace: " + stackTrace);
            Console.WriteLine("Help link: " + helpLink);
            Console.WriteLine("Target site's name: " + siteName);
            Console.WriteLine("Base exception message: " +
                              baseExceptionMessage);
            Console.WriteLine("Inner exception message: " +
                              innerExceptionMessage);
        }
    }
Exemple #27
0
 public void EncodeOID_TooShort()
 {
     // invalid OID - must have at least 2 parts (according to X.208)
     byte[] tooShortOID = CryptoConfig.EncodeOID("0");
 }
        public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
        {
            if (findValue == null)
            {
                throw new ArgumentNullException("findValue");
            }

            string            str = String.Empty;
            string            oid = String.Empty;
            X509KeyUsageFlags ku  = X509KeyUsageFlags.None;
            DateTime          dt  = DateTime.MinValue;

            switch (findType)
            {
            case X509FindType.FindByThumbprint:
            case X509FindType.FindBySubjectName:
            case X509FindType.FindBySubjectDistinguishedName:
            case X509FindType.FindByIssuerName:
            case X509FindType.FindByIssuerDistinguishedName:
            case X509FindType.FindBySerialNumber:
            case X509FindType.FindByTemplateName:
            case X509FindType.FindBySubjectKeyIdentifier:
                try {
                    str = (string)findValue;
                }
                catch (Exception e) {
                    string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.",
                                                findValue.GetType(), "string");
                    throw new CryptographicException(msg, e);
                }
                break;

            case X509FindType.FindByApplicationPolicy:
            case X509FindType.FindByCertificatePolicy:
            case X509FindType.FindByExtension:
                try {
                    oid = (string)findValue;
                }
                catch (Exception e) {
                    string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.",
                                                findValue.GetType(), "X509KeyUsageFlags");
                    throw new CryptographicException(msg, e);
                }
                // OID validation
                try {
                    CryptoConfig.EncodeOID(oid);
                }
                catch (CryptographicUnexpectedOperationException) {
                    string msg = Locale.GetText("Invalid OID value '{0}'.", oid);
                    throw new ArgumentException("findValue", msg);
                }
                break;

            case X509FindType.FindByKeyUsage:
                try {
                    ku = (X509KeyUsageFlags)findValue;
                }
                catch (Exception e) {
                    string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.",
                                                findValue.GetType(), "X509KeyUsageFlags");
                    throw new CryptographicException(msg, e);
                }
                break;

            case X509FindType.FindByTimeValid:
            case X509FindType.FindByTimeNotYetValid:
            case X509FindType.FindByTimeExpired:
                try {
                    dt = (DateTime)findValue;
                }
                catch (Exception e) {
                    string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.",
                                                findValue.GetType(), "X509DateTime");
                    throw new CryptographicException(msg, e);
                }
                break;

            default:
            {
                string msg = Locale.GetText("Invalid find type '{0}'.", findType);
                throw new CryptographicException(msg);
            }
            }

            CultureInfo cinv = CultureInfo.InvariantCulture;
            X509Certificate2Collection results = new  X509Certificate2Collection();

            foreach (X509Certificate2 x in InnerList)
            {
                bool value_match = false;

                switch (findType)
                {
                case X509FindType.FindByThumbprint:
                    // works with Thumbprint, GetCertHashString in both normal (upper) and lower case
                    value_match = ((String.Compare(str, x.Thumbprint, true, cinv) == 0) ||
                                   (String.Compare(str, x.GetCertHashString(), true, cinv) == 0));
                    break;

                case X509FindType.FindBySubjectName:
                    string [] names = x.SubjectName.Format(true).Split(newline_split, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string name in names)
                    {
                        int pos = name.IndexOf('=');
                        value_match = (name.IndexOf(str, pos, StringComparison.InvariantCultureIgnoreCase) >= 0);
                        if (value_match)
                        {
                            break;
                        }
                    }
                    break;

                case X509FindType.FindBySubjectDistinguishedName:
                    value_match = (String.Compare(str, x.Subject, true, cinv) == 0);
                    break;

                case X509FindType.FindByIssuerName:
                    string iname = x.GetNameInfo(X509NameType.SimpleName, true);
                    value_match = (iname.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    break;

                case X509FindType.FindByIssuerDistinguishedName:
                    value_match = (String.Compare(str, x.Issuer, true, cinv) == 0);
                    break;

                case X509FindType.FindBySerialNumber:
                    value_match = (String.Compare(str, x.SerialNumber, true, cinv) == 0);
                    break;

                case X509FindType.FindByTemplateName:
                    // TODO - find a valid test case
                    break;

                case X509FindType.FindBySubjectKeyIdentifier:
                    value_match = (String.Compare(str, GetKeyIdentifier(x), true, cinv) == 0);
                    break;

                case X509FindType.FindByApplicationPolicy:
                    // note: include when no extensions are present (even if v3)
                    value_match = (x.Extensions.Count == 0);
                    // TODO - find test case with extension
                    break;

                case X509FindType.FindByCertificatePolicy:
                    // TODO - find test case with extension
                    break;

                case X509FindType.FindByExtension:
                    value_match = (x.Extensions [oid] != null);
                    break;

                case X509FindType.FindByKeyUsage:
                    X509KeyUsageExtension kue = (x.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
                    if (kue == null)
                    {
                        // key doesn't have any hard coded limitations
                        // note: MS doesn't check for ExtendedKeyUsage
                        value_match = true;
                    }
                    else
                    {
                        value_match = ((kue.KeyUsages & ku) == ku);
                    }
                    break;

                case X509FindType.FindByTimeValid:
                    value_match = ((dt >= x.NotBefore) && (dt <= x.NotAfter));
                    break;

                case X509FindType.FindByTimeNotYetValid:
                    value_match = (dt < x.NotBefore);
                    break;

                case X509FindType.FindByTimeExpired:
                    value_match = (dt > x.NotAfter);
                    break;
                }

                if (!value_match)
                {
                    continue;
                }

                if (validOnly)
                {
                    try {
                        if (x.Verify())
                        {
                            results.Add(x);
                        }
                    }
                    catch {
                    }
                }
                else
                {
                    results.Add(x);
                }
            }
            return(results);
        }
Exemple #29
0
 // LAMESPEC: OID with numbers > Int32 aren't supported by the MS BCL
 public void EncodeOID_BiggerThanInt32()
 {
     // "ms"-invalid OID - where a number of the OID > Int32
     byte[] tooLongOID = CryptoConfig.EncodeOID("1.1.4294967295");
 }
Exemple #30
0
 public void EncodeOIDNull()
 {
     byte[] o = CryptoConfig.EncodeOID(null);
 }