/// <summary>
        /// 数字签名处理.
        /// </summary>
        /// <param name="HashToSign"></param>
        /// <param name="DSAKeyInfo"></param>
        /// <param name="HashAlg"></param>
        /// <returns></returns>
        public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo, string HashAlg)
        {
            try
            {
                //Create a new instance of DSACryptoServiceProvider.
                DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

                //Import the key information.
                DSA.ImportParameters(DSAKeyInfo);

                //Create an DSASignatureFormatter object and pass it the
                //DSACryptoServiceProvider to transfer the private key.
                DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);

                //Set the hash algorithm to the passed value.
                DSAFormatter.SetHashAlgorithm(HashAlg);

                //Create a signature for HashValue and return it.
                return DSAFormatter.CreateSignature(HashToSign);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

                return null;
            }
        }
Beispiel #2
0
		public override void FromXmlString (string xmlString) 
		{
			if (xmlString == null)
				throw new ArgumentNullException ("xmlString");
			
			DSAParameters dsaParams = new DSAParameters ();
			try {
				dsaParams.P = GetNamedParam (xmlString, "P");
				dsaParams.Q = GetNamedParam (xmlString, "Q");
				dsaParams.G = GetNamedParam (xmlString, "G");
				dsaParams.J = GetNamedParam (xmlString, "J");
				dsaParams.Y = GetNamedParam (xmlString, "Y");
				dsaParams.X = GetNamedParam (xmlString, "X");
				dsaParams.Seed = GetNamedParam (xmlString, "Seed");
				byte[] counter = GetNamedParam (xmlString, "PgenCounter");
				if (counter != null) {
					byte[] counter4b = new byte [4]; // always 4 bytes
					Buffer.BlockCopy (counter, 0, counter4b, 0, counter.Length);
					dsaParams.Counter = BitConverterLE.ToInt32 (counter4b, 0);
				}
				ImportParameters (dsaParams);
			}
			catch {
				ZeroizePrivateKey (dsaParams);
				throw;
			}
			finally	{
				ZeroizePrivateKey (dsaParams);
			}
		}
            public override void ImportParameters(DSAParameters parameters)
            {
                if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null)
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields);

                // J is not required and is not even used on CNG blobs. It should however be less than P (J == (P-1) / Q). This validation check
                // is just to maintain parity with DSACryptoServiceProvider, which also performs this check.
                if (parameters.J != null && parameters.J.Length >= parameters.P.Length)
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ);

                bool hasPrivateKey = parameters.X != null;

                int keySizeInBytes = parameters.P.Length;
                int keySizeInBits = keySizeInBytes * 8;

                if (parameters.G.Length != keySizeInBytes || parameters.Y.Length != keySizeInBytes)
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);

                if (hasPrivateKey && parameters.X.Length != parameters.Q.Length)
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);

                byte[] blob;
                if (keySizeInBits <= MaxV1KeySize)
                {
                    GenerateV1DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey);
                }
                else
                {
                    GenerateV2DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey);
                }

                ImportKeyBlob(blob, hasPrivateKey);
            }
Beispiel #4
0
        //-------------------------------------------------------------------------
        // Шифруем закрытым ключем Хеш-таблицу
        public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo,
        string HashAlg)
        {
            byte[] sig = null;

            try
            {
            // Создаем новыый экземпляр класса
            using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
            {
                // Импортируем ключи, в данном случае закрытый ключ
                DSA.ImportParameters(DSAKeyInfo);

                // Создаем объект класса DSASignatureFormatter и передаем ему DSACryptoServiceProvider закрытый ключ
                DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);

                // Устанавливаем алгоритм шифрования
                DSAFormatter.SetHashAlgorithm(HashAlg);

                // Создаем подпись для хеш-таблицы и возвращаем ее значение
                sig = DSAFormatter.CreateSignature(HashToSign);
            }
            }
            catch (CryptographicException e)
            {
            Console.WriteLine(e.Message);
            }

            return sig;
        }
        private static bool DSAVerifyHash(byte[] HashValue, byte[] SignedHashValue, DSAParameters publickeyinfo, string HashAlg)
        {
            bool verified = false;

            try
            {
                //Create a new instance of DSACryptoServiceProvider
                using(DSACryptoServiceProvider dsa = new DSACryptoServiceProvider())
                {
                    //Import the key information
                    dsa.ImportParameters(publickeyinfo);

                    // Create an DSASignatureDeformatter object and pass it the DSACryptoServiceProvider to transfer the private key.
                    //DSASignatureDeformatter dsaDeformatter = new DSASignatureDeformatter(dsa);

                    //Set the hash algorithm to the passed value.
                    //dsaDeformatter.SetHashAlgorithm(HashAlg);

                    //Verify signature and return the result
                               //Verify hashed files                        //Verify hashed data 
                    verified = dsa.VerifyData(HashValue, SignedHashValue); //dsaDeformatter.VerifySignature(HashValue, SignedHashValue);

                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return verified;
        }
        public void DigitalSignatureAlgorithm_compare_parameters_generation_with_original_Pidgin_OffTheRecord_data()
        {
            // Arrange
            const string p =
                "AEC0FBB4CEA96EF8BDD0E91D1BA2F6641B6535CBDA8D739CC2898FE7B472865AB60AD2B1BAA2368603C7439E63BC2F2F33D422E70173F70DB738DF5979EAEAF3CAC343CBF711960E16786703C80DF0734D8330DC955DA84B521DAB5C729202F1244D805E6BF2CC7A7142CAD74BE5FFFC14B9CCB6CABB7DB10A8F2DDB4E82383F";
            const string q = "A2A2BC20E2D94C44C63608479C79068CE7914EF3";
            const string g =
                "69B9FC5A73F3F6EA3A86F8FA3A203F42DACDC3A1516002025E5765A9DCB975F348ACBBA2116230E19CE3FC5256546FD168A2940809BDA8655771967E9CD90AF44D2C20F97F448494213A775E23607F33C255A9A74E2A5FC7B4D50BAD024D7EFAC282E67332D51A5F69239011FE058D7E75E97A788FBD5B3BAD796B2C6D8C6C3E";
            const string y =
                "9931144F3059D92FCB2AAC03B130DAE43ED1EF30AA2F0E670C3974C3E80C7110D1A60210F92479D7F640C20E1F16E01B4A72FF8D45443B01EBE2D67DF49791CAC6191B159AC39446EB6A2EA597B6B678CC3157AECEAB12A804CF0772068A942EC819138EDD6005620FE746522FF408BBC8211ABD9D6016AA46EEC87F3F04CFA4";
            const string x = "48BFDA215C31A9F0B226B3DB11F862450A0F30DA"; /* private key */

            // Act
            var param = new DSAParameters();
            param.X = General.StringToByteArray(x);
            param.P = General.StringToByteArray(p);
            param.Q = General.StringToByteArray(q);
            param.G = General.StringToByteArray(g);
            param.Y = General.StringToByteArray(y);

            var dsa = new DSACryptoServiceProvider(1024);
            dsa.ImportParameters(param);
            DSAParameters output = dsa.ExportParameters(true);

            // Assert
            param.X.SequenceEqual(output.X).Should().BeTrue();
            param.P.SequenceEqual(output.P).Should().BeTrue();
            param.Q.SequenceEqual(output.Q).Should().BeTrue();
            param.G.SequenceEqual(output.G).Should().BeTrue();
            param.Y.SequenceEqual(output.Y).Should().BeTrue();
        }
Beispiel #7
0
        //-------------------------------------------------------------------
        public static bool DSAVerifyHash(byte[] HashValue, byte[] SignedHashValue,
        DSAParameters DSAKeyInfo, string HashAlg)
        {
            bool verified = false;

            try
            {
            // Создаем новый экземпляр класса DSACryptoServiceProvider.
            using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
            {
                // Импортируем ключи
                DSA.ImportParameters(DSAKeyInfo);

                //Создаем объект класса DSASignatureFormatter и передаем ему DSACryptoServiceProvider закрытый ключ
                DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);

                // Устанавливаем алгоритм шифрования
                DSADeformatter.SetHashAlgorithm(HashAlg);

                // Сверяем подписи и возвращаем результат
                verified = DSADeformatter.VerifySignature(HashValue, SignedHashValue);
            }
            }
            catch (CryptographicException e)
            {
            Console.WriteLine(e.Message);
            }

            return verified;
        }
        /// <summary>
        /// Gets the signature.
        /// </summary>
        /// <param name="key">The key data bytes.</param>
        /// <returns></returns>
        public override byte[] GetSignature(IEnumerable<byte> key)
        {
            var data = key.ToArray();
            //using (var sha1 = new Renci.SshNet.Security.Cryptography.SHA1Hash())
            using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
            {
                using (var cs = new System.Security.Cryptography.CryptoStream(System.IO.Stream.Null, sha1, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                }

                var dsaKeyInfo = new System.Security.Cryptography.DSAParameters();

                dsaKeyInfo.X = this._privateKey.TrimLeadingZero().ToArray();
                dsaKeyInfo.P = this._p.TrimLeadingZero().ToArray();
                dsaKeyInfo.Q = this._q.TrimLeadingZero().ToArray();
                dsaKeyInfo.G = this._g.TrimLeadingZero().ToArray();

                using (var DSA = new System.Security.Cryptography.DSACryptoServiceProvider())
                {
                    DSA.ImportParameters(dsaKeyInfo);
                    var DSAFormatter = new DSASignatureFormatter(DSA);
                    DSAFormatter.SetHashAlgorithm("SHA1");

                    var signature = DSAFormatter.CreateSignature(sha1);

                    return new SignatureKeyData
                    {
                        AlgorithmName = this.Name,
                        Signature = signature,
                    }.GetBytes().ToArray();
                }
            }
        }
 public override void FromXmlString(string xmlString)
 {
     if (xmlString == null)
     {
         throw new ArgumentNullException("xmlString");
     }
     DSAParameters parameters = new DSAParameters();
     SecurityElement topElement = new Parser(xmlString).GetTopElement();
     string inputBuffer = topElement.SearchForTextOfLocalName("P");
     if (inputBuffer == null)
     {
         throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[] { "DSA", "P" }));
     }
     parameters.P = Convert.FromBase64String(Utils.DiscardWhiteSpaces(inputBuffer));
     string str2 = topElement.SearchForTextOfLocalName("Q");
     if (str2 == null)
     {
         throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[] { "DSA", "Q" }));
     }
     parameters.Q = Convert.FromBase64String(Utils.DiscardWhiteSpaces(str2));
     string str3 = topElement.SearchForTextOfLocalName("G");
     if (str3 == null)
     {
         throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[] { "DSA", "G" }));
     }
     parameters.G = Convert.FromBase64String(Utils.DiscardWhiteSpaces(str3));
     string str4 = topElement.SearchForTextOfLocalName("Y");
     if (str4 == null)
     {
         throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[] { "DSA", "Y" }));
     }
     parameters.Y = Convert.FromBase64String(Utils.DiscardWhiteSpaces(str4));
     string str5 = topElement.SearchForTextOfLocalName("J");
     if (str5 != null)
     {
         parameters.J = Convert.FromBase64String(Utils.DiscardWhiteSpaces(str5));
     }
     string str6 = topElement.SearchForTextOfLocalName("X");
     if (str6 != null)
     {
         parameters.X = Convert.FromBase64String(Utils.DiscardWhiteSpaces(str6));
     }
     string str7 = topElement.SearchForTextOfLocalName("Seed");
     string str8 = topElement.SearchForTextOfLocalName("PgenCounter");
     if ((str7 != null) && (str8 != null))
     {
         parameters.Seed = Convert.FromBase64String(Utils.DiscardWhiteSpaces(str7));
         parameters.Counter = Utils.ConvertByteArrayToInt(Convert.FromBase64String(Utils.DiscardWhiteSpaces(str8)));
     }
     else if ((str7 != null) || (str8 != null))
     {
         if (str7 == null)
         {
             throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[] { "DSA", "Seed" }));
         }
         throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[] { "DSA", "PgenCounter" }));
     }
     this.ImportParameters(parameters);
 }
Beispiel #10
0
        // We can provide a default implementation of FromXmlString because we require 
        // every DSA implementation to implement ImportParameters
        // All we have to do here is parse the XML. 
 
        public override void FromXmlString(String xmlString) {
            if (xmlString == null) throw new ArgumentNullException("xmlString"); 
            Contract.EndContractBlock();
            DSAParameters dsaParams = new DSAParameters();
            Parser p = new Parser(xmlString);
            SecurityElement topElement = p.GetTopElement(); 

            // P is always present 
            String pString = topElement.SearchForTextOfLocalName("P"); 
            if (pString == null) {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString","DSA","P")); 
            }
            dsaParams.P = Convert.FromBase64String(Utils.DiscardWhiteSpaces(pString));

            // Q is always present 
            String qString = topElement.SearchForTextOfLocalName("Q");
            if (qString == null) { 
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString","DSA","Q")); 
            }
            dsaParams.Q = Convert.FromBase64String(Utils.DiscardWhiteSpaces(qString)); 

            // G is always present
            String gString = topElement.SearchForTextOfLocalName("G");
            if (gString == null) { 
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString","DSA","G"));
            } 
            dsaParams.G = Convert.FromBase64String(Utils.DiscardWhiteSpaces(gString)); 

            // Y is always present 
            String yString = topElement.SearchForTextOfLocalName("Y");
            if (yString == null) {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString","DSA","Y"));
            } 
            dsaParams.Y = Convert.FromBase64String(Utils.DiscardWhiteSpaces(yString));
 
            // J is optional 
            String jString = topElement.SearchForTextOfLocalName("J");
            if (jString != null) dsaParams.J = Convert.FromBase64String(Utils.DiscardWhiteSpaces(jString)); 

            // X is optional -- private key if present
            String xString = topElement.SearchForTextOfLocalName("X");
            if (xString != null) dsaParams.X = Convert.FromBase64String(Utils.DiscardWhiteSpaces(xString)); 

            // Seed and PgenCounter are optional as a unit -- both present or both absent 
            String seedString = topElement.SearchForTextOfLocalName("Seed"); 
            String pgenCounterString = topElement.SearchForTextOfLocalName("PgenCounter");
            if ((seedString != null) && (pgenCounterString != null)) { 
                dsaParams.Seed = Convert.FromBase64String(Utils.DiscardWhiteSpaces(seedString));
                dsaParams.Counter = Utils.ConvertByteArrayToInt(Convert.FromBase64String(Utils.DiscardWhiteSpaces(pgenCounterString)));
            } else if ((seedString != null) || (pgenCounterString != null)) {
                if (seedString == null) { 
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString","DSA","Seed"));
                } else { 
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString","DSA","PgenCounter")); 
                }
            } 

            ImportParameters(dsaParams);
        }
        public static DsaPublicKeyParameters GetDsaPublicKey(DSAParameters dp)
        {
            DsaValidationParameters validationParameters = (dp.Seed != null) ? new DsaValidationParameters(dp.Seed, dp.Counter) : null;

            var parameters = new DsaParameters(new BigInteger(1, dp.P), new BigInteger(1, dp.Q), new BigInteger(1, dp.G), validationParameters);

            return new DsaPublicKeyParameters(new BigInteger(1, dp.Y), parameters);
        }
Beispiel #12
0
        private void Enregister()
        {
            mycrypto = new DSACryptoServiceProvider();
            ASCIIEncoding encoding = new ASCIIEncoding();

            _publicKey = mycrypto.ExportParameters(false);
            byte[] tab = encoding.GetBytes(_pseudo);
            byte[] hash = mycrypto.SignData(tab);
            _myServer.ReceiveKey(tab, hash, _publicKey);
        }
Beispiel #13
0
		public override PrivateKey GeneratePrivate (KeySpec key)
		{
			DSAPrivateKeySpec spec = (DSAPrivateKeySpec) key;
			DSAParameters dsp = new DSAParameters ();
			dsp.G = spec.GetG ().GetBytes ();
			dsp.P = spec.GetP ().GetBytes ();
			dsp.Q = spec.GetQ ().GetBytes ();
			dsp.X = spec.GetX ().GetBytes ();
			return new DSAPrivateKey (dsp);
		}
 static CryptographyParams()
 {
     dsap = new DSAParameters();
     dsap.Counter = 380;
     dsap.G = new byte[] { 0x4E, 0x6F, 0xE7, 0x44, 0xDD, 0x60, 0x88, 0xFF, 0x2A, 0x72, 0x45, 0x70, 0xC3, 0x43, 0xE0, 0x9D, 0xCA, 0x11, 0x0F, 0x38, 0x06, 0xB2, 0xBE, 0x96, 0x72, 0xB8, 0xD2, 0xD5, 0xEB, 0xF7, 0xD3, 0xD2, 0x9B, 0xFE, 0x8A, 0x10, 0xFB, 0x93, 0xB1, 0x76, 0xBB, 0x7D, 0xAC, 0x6B, 0x0E, 0xAE, 0xD3, 0x9E, 0x73, 0xCA, 0x9C, 0x29, 0x01, 0x84, 0xA4, 0x97, 0xB4, 0x59, 0xA1, 0x65, 0x9F, 0xD6, 0x0B, 0x94 };
     dsap.J = new byte[] { 0xBB, 0x6C, 0x04, 0xD1, 0xCD, 0x7B, 0xDF, 0xB4, 0x4D, 0x70, 0xDC, 0x1E, 0xBD, 0xC8, 0xA3, 0x21, 0xB5, 0xA0, 0x80, 0xBC, 0xF1, 0xA6, 0x61, 0xBA, 0x51, 0x11, 0x15, 0xD4, 0x86, 0xEC, 0x28, 0x55, 0x7E, 0x2A, 0x21, 0xAD, 0xFF, 0x96, 0xEB, 0x8C, 0xB1, 0xF4, 0xA0, 0x5A };
     dsap.P = new byte[] { 0x81, 0x66, 0x5B, 0xF0, 0x6C, 0x13, 0x07, 0x62, 0xEC, 0x5E, 0xB8, 0x8E, 0xEE, 0x76, 0xF2, 0x32, 0x4C, 0x01, 0x7B, 0x81, 0x45, 0x08, 0x22, 0x5D, 0x79, 0x6F, 0x3B, 0x88, 0x07, 0x43, 0x75, 0x23, 0x9D, 0x62, 0xB6, 0x7F, 0xE5, 0xC4, 0x01, 0x4F, 0x63, 0xAE, 0x7B, 0x58, 0xA9, 0x2C, 0x70, 0xF3, 0x2A, 0xFD, 0x2E, 0x72, 0xF3, 0x90, 0x01, 0x6B, 0xCF, 0x68, 0xE5, 0x46, 0x54, 0xD5, 0xED, 0x8F };
     dsap.Q = new byte[] { 0xB0, 0xBF, 0x5B, 0x8F, 0xAD, 0xC5, 0x15, 0x3D, 0x52, 0x90, 0x1B, 0x7D, 0x58, 0x6A, 0x1F, 0x5E, 0x47, 0x09, 0xC7, 0x43 };
     dsap.Seed = new byte[] { 0xA0, 0x13, 0xA1, 0x17, 0x47, 0x9D, 0x0B, 0x7B, 0x2C, 0xA5, 0x70, 0x72, 0xF4, 0x88, 0x72, 0x89, 0x54, 0x12, 0x4C, 0x64 };
     dsap.Y = new byte[] { 0x20, 0xA5, 0x63, 0x06, 0xA2, 0x59, 0xA1, 0x2F, 0x6B, 0xE3, 0x49, 0x83, 0x29, 0x8D, 0x5A, 0xA7, 0x8B, 0x9E, 0xF8, 0x33, 0x32, 0xE9, 0xB5, 0xFB, 0x52, 0xF3, 0xD3, 0xB4, 0x7B, 0xEA, 0xDB, 0xC1, 0xB5, 0x8E, 0x89, 0x47, 0x29, 0x4C, 0xD9, 0x33, 0xD0, 0xA8, 0xDA, 0x1E, 0x93, 0x70, 0x80, 0x3D, 0x55, 0x60, 0x35, 0x95, 0x6F, 0xD9, 0xD4, 0xD1, 0x5E, 0x06, 0x41, 0x3E, 0x3E, 0xEC, 0xD6, 0x14 };
 }
	// may also help for DSA descendants
	public void AssertEquals (string message, DSAParameters expectedKey, DSAParameters actualKey, bool checkPrivateKey) 
	{
		Assert.AreEqual (expectedKey.Counter, actualKey.Counter, message + " Counter");
		AssertEquals (message + " G", expectedKey.G, actualKey.G);
		AssertEquals (message + " J", expectedKey.J, actualKey.J);
		AssertEquals (message + " P", expectedKey.P, actualKey.P);
		AssertEquals (message + " Q", expectedKey.Q, actualKey.Q);
		AssertEquals (message + " Seed", expectedKey.Seed, actualKey.Seed);
		AssertEquals (message + " Y", expectedKey.Y, actualKey.Y);
		if (checkPrivateKey)
			AssertEquals (message + " X", expectedKey.X, actualKey.X);
	}
        public static AsymmetricCipherKeyPair GetDsaKeyPair(DSAParameters dp)
        {
            DsaValidationParameters validationParameters = (dp.Seed != null) ? new DsaValidationParameters(dp.Seed, dp.Counter) : null;

            var parameters = new DsaParameters(new BigInteger(1, dp.P), new BigInteger(1, dp.Q), new BigInteger(1, dp.G), validationParameters);

            var pubKey = new DsaPublicKeyParameters(new BigInteger(1, dp.Y), parameters);

            var privKey = new DsaPrivateKeyParameters(new BigInteger(1, dp.X), parameters);

            return new AsymmetricCipherKeyPair(pubKey, privKey);
        }
Beispiel #17
0
		// basic implementation for tests
		public override void ImportParameters (DSAParameters parameters)
		{
			dsa.P = parameters.P;
			dsa.Q = parameters.Q;
			dsa.G = parameters.G;
			dsa.J = parameters.J;
			dsa.Y = parameters.Y;
			if (parameters.X != null) {
				// watch out for private key zeroification
				dsa.X = (byte []) parameters.X.Clone ();
			}
			dsa.Seed = parameters.Seed;
			dsa.Counter = parameters.Counter;
		}
Beispiel #18
0
        internal PrivateKey(DSAParameters dsaParameters)
        {
            privateKey = dsaParameters;

            var dsa = new DSACryptoServiceProvider(1024);
            dsa.ImportParameters(privateKey);
            PublicKey = dsa.ExportParameters(false);

            PublicKeyAsMPI = MultiPrecisionInteger.ByteArrayToMpi(PublicKey.P)
                .Concat(MultiPrecisionInteger.ByteArrayToMpi(PublicKey.Q))
                .Concat(MultiPrecisionInteger.ByteArrayToMpi(PublicKey.G))
                .Concat(MultiPrecisionInteger.ByteArrayToMpi(PublicKey.Y))
                .ToArray();
        }
Beispiel #19
0
        /// <summary>
        /// Methode permetant de recreer une cle publique avec les arguments de la webmethod
        /// en effet il sera difficile de passer directement une instance DSAParameters
        /// car il y aura des conflits avec les classes utilisant directement le DSAParameters
        /// </summary>
        /// <param name="counter"></param>
        /// <param name="G"></param>
        /// <param name="J"></param>
        /// <param name="P"></param>
        /// <param name="Q"></param>
        /// <param name="Seed"></param>
        /// <param name="X"></param>
        /// <param name="Y"></param>
        /// <returns>
        /// La cle publique reconstitue
        /// </returns>
        public static DSAParameters RecreateKey(int counter, byte[] G, byte[] J, byte[] P, byte[] Q, byte[] Seed, byte[] X, byte[] Y)
        {
            //Regeneration de la cle publique
            DSAParameters key = new DSAParameters();
            key.Counter = counter;
            key.G = G;
            key.J = J;
            key.P = P;
            key.Q = Q;
            key.Seed = Seed;
            key.X = X;
            key.Y = Y;

            return key;
        }
Beispiel #20
0
        public override void LoadKeyAndCertificatesData(byte[] data)
        {
            using (var worker = new SshDataWorker(data))
            {
                if (worker.ReadString(Encoding.ASCII) != this.Name)
                    throw new CryptographicException("Key and certificates were not created with this algorithm.");

                var args = new DSAParameters();
                args.P = worker.ReadMpint();
                args.Q = worker.ReadMpint();
                args.G = worker.ReadMpint();
                args.Y = worker.ReadMpint();

                _algorithm.ImportParameters(args);
            }
        }
Beispiel #21
0
        public bool ReceiveKey(byte[] pseudo,byte[] hash, DSAParameters key )
        {
            bool ret = false;
            ASCIIEncoding codage = new ASCIIEncoding();
            DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider();
            mycrypto.ImportParameters(key);
            if(mycrypto.VerifyData(pseudo,hash))
            {

                string nick = codage.GetString(pseudo);
                _clients.Add(nick, key);
                ret = true;
            }

            return ret;
        }
Beispiel #22
0
        /// <summary>
        ///   Gets the largest size, in bytes, for a signature produced by this key in the indicated format.
        /// </summary>
        /// <param name="signatureFormat">The encoding format for a signature.</param>
        /// <returns>
        ///   The largest size, in bytes, for a signature produced by this key in the indicated format.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">
        ///   <paramref name="signatureFormat"/> is not a known format.
        /// </exception>
        public int GetMaxSignatureSize(DSASignatureFormat signatureFormat)
        {
            DSAParameters dsaParameters = ExportParameters(false);
            int           qLength       = dsaParameters.Q !.Length;

            switch (signatureFormat)
            {
            case DSASignatureFormat.IeeeP1363FixedFieldConcatenation:
                return(qLength * 2);

            case DSASignatureFormat.Rfc3279DerSequence:
                return(AsymmetricAlgorithmHelpers.GetMaxDerSignatureSize(fieldSizeBits: qLength * 8));

            default:
                throw new ArgumentOutOfRangeException(nameof(signatureFormat));
            }
        }
Beispiel #23
0
        public override DSAParameters ExportParameters(bool includePrivateParameters)
        {
            // It's entirely possible that this line will cause the key to be generated in the first place.
            SafeDsaHandle key = _key.Value;

            CheckInvalidKey(key);

            DSAParameters dsaParameters = Interop.Crypto.ExportDsaParameters(key, includePrivateParameters);
            bool          hasPrivateKey = dsaParameters.X != null;

            if (hasPrivateKey != includePrivateParameters)
            {
                throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
            }

            return(dsaParameters);
        }
Beispiel #24
0
        public override void ImportParameters(DSAParameters parameters)
        {
            if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields);
            }

            // J is not required and is not even used on CNG blobs. It should however be less than P (J == (P-1) / Q). This validation check
            // is just to maintain parity with DSACNG and DSACryptoServiceProvider, which also perform this check.
            if (parameters.J != null && parameters.J.Length >= parameters.P.Length)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ);
            }

            bool hasPrivateKey = parameters.X != null;

            int keySize = parameters.P.Length;

            if (parameters.G.Length != keySize || parameters.Y.Length != keySize)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);
            }

            if (hasPrivateKey && parameters.X !.Length != parameters.Q.Length)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);
            }

            ThrowIfDisposed();

            SafeDsaHandle key;

            if (!Interop.Crypto.DsaKeyCreateByExplicitParameters(
                    out key,
                    parameters.P, parameters.P.Length,
                    parameters.Q, parameters.Q.Length,
                    parameters.G, parameters.G.Length,
                    parameters.Y, parameters.Y.Length,
                    parameters.X, parameters.X != null ? parameters.X.Length : 0))
            {
                throw Interop.Crypto.CreateOpenSslCryptographicException();
            }

            SetKey(key);
        }
Beispiel #25
0
        private static void WriteDSSSeed(DSAParameters dsaParameters, BinaryWriter bw)
        {
            if (dsaParameters.Seed == null || dsaParameters.Seed.Length == 0)
            {
                bw.Write(0xFFFFFFFF); // counter

                // seed[20] needs to be all 0xFF
                for (int i = 0; i < 20; i += sizeof(uint))
                {
                    bw.Write(0xFFFFFFFF);
                }
            }
            else
            {
                bw.Write((int)dsaParameters.Counter);
                bw.WriteReversed(dsaParameters.Seed);
            }
        }
Beispiel #26
0
        internal static void ReadSubjectPublicKeyInfo(
            this DerSequenceReader algParameters,
            byte[] publicKeyBlob,
            ref DSAParameters parameters)
        {
            parameters.P = algParameters.ReadIntegerBytes();
            parameters.Q = algParameters.ReadIntegerBytes();
            parameters.G = algParameters.ReadIntegerBytes();

            DerSequenceReader privateKeyReader = DerSequenceReader.CreateForPayload(publicKeyBlob);
            parameters.Y = privateKeyReader.ReadIntegerBytes();

            KeyBlobHelpers.TrimPaddingByte(ref parameters.P);
            KeyBlobHelpers.TrimPaddingByte(ref parameters.Q);

            KeyBlobHelpers.PadOrTrim(ref parameters.G, parameters.P.Length);
            KeyBlobHelpers.PadOrTrim(ref parameters.Y, parameters.P.Length);
        }
Beispiel #27
0
        /// <summary>
        /// Constructeur par defaut
        /// </summary>
        public PrincipalForm()
        {
            InitializeComponent();
            SaveForm param_fenetre = Serializer.DeserialiserFenetre();
            if (param_fenetre != null)
            {
                this.Size = new System.Drawing.Size(param_fenetre.Weightform, param_fenetre.Heightform);
                this.splitContainer1.SplitterDistance = param_fenetre.Splitterdistance;
                this.Location = new System.Drawing.Point(param_fenetre.LocalisationX, param_fenetre.LocalisationY);
            }

            //initialisation de liaison avec le service
            client = new ServeurChat.ServeurChatSoapClient();
            //generation des clé pour la session qui va etre lance
            crypto = new DSACryptoServiceProvider();
            securitykey = crypto.ExportParameters(false);
            connected = false;
        }
Beispiel #28
0
        public override void LoadKeyAndCertificatesData(byte[] data)
        {
            using (var dataReader = new SshStreamReader(new MemoryStream(data)))
            {
                // Read parameters from stream.
                var algParams = new DSAParameters();

                if (dataReader.ReadString() != this.Name) throw new CryptographicException(
                   "Key and certificates were not created with this algorithm.");
                algParams.P = dataReader.ReadMPInt();
                algParams.Q = dataReader.ReadMPInt();
                algParams.G = dataReader.ReadMPInt();
                algParams.Y = dataReader.ReadMPInt();

                // Import parameters for algorithm key.
                _algorithm.ImportParameters(algParams);
            }
        }
Beispiel #29
0
        private static void GenerateV1DsaBlob(BinaryWriter bw, DSAParameters parameters, int keySizeInBytes, bool hasPrivateKey)
        {
            // Write out a (V1) BCRYPT_DSA_KEY_BLOB
            bw.Write((int)(hasPrivateKey ? KeyBlobMagicNumber.DsaPrivate : KeyBlobMagicNumber.DsaPublic));
            bw.Write((int)keySizeInBytes);

            if (parameters.Seed != null)
            {
                // The Seed length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message.
                if (parameters.Seed.Length != Sha1HashOutputSize)
                {
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey);
                }

                bw.Write((byte[])(ToBigEndian(parameters.Counter)));
                bw.Write(parameters.Seed);
            }
            else
            {
                // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject
                // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng.
                bw.Write((uint)0xffffffff);
                for (int i = 0; i < Sha1HashOutputSize; i++)
                {
                    bw.Write((byte)0xff);
                }
            }

            // The Q length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message.
            if (parameters.Q.Length != Sha1HashOutputSize)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey);
            }

            bw.Write(parameters.Q);
            bw.Write(parameters.P);
            bw.Write(parameters.G);
            bw.Write(parameters.Y);
            if (hasPrivateKey)
            {
                bw.Write(parameters.X);
            }
        }
Beispiel #30
0
        // PublicKeyInfo (X.509 compatible) message
        /// <summary>
        /// Returns the AsnMessage representing the X.509 PublicKeyInfo.
        /// </summary>
        /// <param name="publicKey">The DSA key to be encoded.</param>
        /// <returns>Returns the AsnType representing the
        /// X.509 PublicKeyInfo.</returns>
        /// <seealso cref="PrivateKeyToPKCS8(DSAParameters)"/>
        /// <seealso cref="PrivateKeyToPKCS8(RSAParameters)"/>
        /// <seealso cref="PublicKeyToX509(RSAParameters)"/>
        public static AsnMessage PublicKeyToX509(DSAParameters publicKey)
        {
            // Value Type cannot be null
            // Debug.Assert(null != publicKey);

            /* *
            * SEQUENCE              // PrivateKeyInfo
            * +- SEQUENCE           // AlgorithmIdentifier
            * |  +- OID             // 1.2.840.10040.4.1
            * |  +- SEQUENCE        // DSS-Params (Optional Parameters)
            * |    +- INTEGER (P)
            * |    +- INTEGER (Q)
            * |    +- INTEGER (G)
            * +- BITSTRING          // PublicKey
            *    +- INTEGER(Y)      // DSAPublicKey Y
            * */

            // DSA Parameters
            AsnType p = CreateIntegerPos(publicKey.P);
            AsnType q = CreateIntegerPos(publicKey.Q);
            AsnType g = CreateIntegerPos(publicKey.G);

            // Sequence - DSA-Params
            AsnType dssParams = CreateSequence(new[] {p, q, g});

            // OID - packed 1.2.840.10040.4.1
            //   { 0x2A, 0x86, 0x48, 0xCE, 0x38, 0x04, 0x01 }
            AsnType oid = CreateOid("1.2.840.10040.4.1");

            // Sequence
            AsnType algorithmID = CreateSequence(new[] {oid, dssParams});

            // Public Key Y
            AsnType y = CreateIntegerPos(publicKey.Y);
            AsnType key = CreateBitString(y);

            // Sequence 'A'
            AsnType publicKeyInfo =
                CreateSequence(new[] {algorithmID, key});

            return new AsnMessage(publicKeyInfo.GetBytes(), "X.509");
        }
            private static SafeSecKeyRefHandle ImportKey(DSAParameters parameters)
            {
                bool hasPrivateKey = parameters.X != null;

                byte[] blob;

                if (hasPrivateKey)
                {
                    Debug.Assert(parameters.X != null);

                    // DSAPrivateKey ::= SEQUENCE(
                    //   version INTEGER,
                    //   p INTEGER,
                    //   q INTEGER,
                    //   g INTEGER,
                    //   y INTEGER,
                    //   x INTEGER,
                    // )

                    using (AsnWriter privateKeyWriter = new AsnWriter(AsnEncodingRules.DER))
                    {
                        privateKeyWriter.PushSequence();
                        privateKeyWriter.WriteInteger(0);
                        privateKeyWriter.WriteKeyParameterInteger(parameters.P);
                        privateKeyWriter.WriteKeyParameterInteger(parameters.Q);
                        privateKeyWriter.WriteKeyParameterInteger(parameters.G);
                        privateKeyWriter.WriteKeyParameterInteger(parameters.Y);
                        privateKeyWriter.WriteKeyParameterInteger(parameters.X);
                        privateKeyWriter.PopSequence();
                        blob = privateKeyWriter.Encode();
                    }
                }
                else
                {
                    using (AsnWriter writer = DSAKeyFormatHelper.WriteSubjectPublicKeyInfo(parameters))
                    {
                        blob = writer.Encode();
                    }
                }

                return(Interop.AppleCrypto.ImportEphemeralKey(blob, hasPrivateKey));
            }
Beispiel #32
0
        public override void FromXmlString(string xmlString)
        {
            if (xmlString == null)
            {
                throw new ArgumentNullException("xmlString");
            }

            DSAParameters dsaParams = new DSAParameters();

            try {
                SecurityParser sp = new SecurityParser();
                sp.LoadXml(xmlString);
                SecurityElement se = sp.ToXml();
                if (se.Tag != "DSAKeyValue")
                {
                    throw new Exception();
                }
                dsaParams.P    = GetNamedParam(se, "P");
                dsaParams.Q    = GetNamedParam(se, "Q");
                dsaParams.G    = GetNamedParam(se, "G");
                dsaParams.J    = GetNamedParam(se, "J");
                dsaParams.Y    = GetNamedParam(se, "Y");
                dsaParams.X    = GetNamedParam(se, "X");
                dsaParams.Seed = GetNamedParam(se, "Seed");
                byte[] counter = GetNamedParam(se, "PgenCounter");
                if (counter != null)
                {
                    byte[] counter4b = new byte [4];                     // always 4 bytes
                    Buffer.BlockCopy(counter, 0, counter4b, 0, counter.Length);
                    dsaParams.Counter = BitConverterLE.ToInt32(counter4b, 0);
                }
                ImportParameters(dsaParams);
            }
            catch {
                ZeroizePrivateKey(dsaParams);
                throw;
            }
            finally {
                ZeroizePrivateKey(dsaParams);
            }
        }
Beispiel #33
0
        public override void ImportParameters(DSAParameters parameters)
        {
            if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields);
            }

            // J is not required and is not even used on CNG blobs. It should however be less than P (J == (P-1) / Q). This validation check
            // is just to maintain parity with DSACryptoServiceProvider, which also performs this check.
            if (parameters.J != null && parameters.J.Length >= parameters.P.Length)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ);
            }

            bool hasPrivateKey = parameters.X != null;

            int keySizeInBytes = parameters.P.Length;
            int keySizeInBits  = keySizeInBytes * 8;

            if (parameters.G.Length != keySizeInBytes || parameters.Y.Length != keySizeInBytes)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);
            }

            if (hasPrivateKey && parameters.X !.Length != parameters.Q.Length)
            {
                throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);
            }

            byte[] blob;
            if (keySizeInBits <= MaxV1KeySize)
            {
                GenerateV1DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey);
            }
            else
            {
                GenerateV2DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey);
            }

            ImportKeyBlob(blob, hasPrivateKey);
        }
Beispiel #34
0
        internal static byte[] ToPrivateKeyBlob(this DSAParameters parameters)
        {
            Debug.Assert(parameters.X != null);

            // DSAPrivateKey ::= SEQUENCE(
            //   version INTEGER,
            //   p INTEGER,
            //   q INTEGER,
            //   g INTEGER,
            //   y INTEGER,
            //   x INTEGER,
            // )

            return(DerEncoder.ConstructSequence(
                       DerEncoder.SegmentedEncodeUnsignedInteger(new byte[] { 0 }),
                       DerEncoder.SegmentedEncodeUnsignedInteger(parameters.P),
                       DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Q),
                       DerEncoder.SegmentedEncodeUnsignedInteger(parameters.G),
                       DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Y),
                       DerEncoder.SegmentedEncodeUnsignedInteger(parameters.X)));
        }
Beispiel #35
0
        private static void WriteKeyBlobHeader(DSAParameters dsaParameters, BinaryWriter bw, bool isPrivate, out bool isV3)
        {
            // Write out the BLOBHEADER (or PUBLICKEYSTRUC).
            isV3 = false;

            // If Y is present and this is a private key,
            // or Y and J are present and this is a public key, this should be a v3 blob.
            byte version = BLOBHEADER_CURRENT_BVERSION;

            if (((dsaParameters.Y != null) && isPrivate) ||
                ((dsaParameters.Y != null) && (dsaParameters.J != null)))
            {
                Debug.Assert(dsaParameters.Y.Length > 0);
                isV3    = true;
                version = 0x3;
            }
            bw.Write((byte)(isPrivate ? PRIVATEKEYBLOB : PUBLICKEYBLOB));  // BLOBHEADER.bType
            bw.Write((byte)version);                                       // BLOBHEADER.bVersion
            bw.Write((ushort)0);                                           // BLOBHEADER.wReserved
            bw.Write((int)CapiHelper.CALG_DSS_SIGN);                       // BLOBHEADER.aiKeyAlg
        }
Beispiel #36
0
            public override DSAParameters ExportParameters(bool includePrivateParameters)
            {
                SecKeyPair keys = GetKeys();

                if (keys.PublicKey == null ||
                    (includePrivateParameters && keys.PrivateKey == null))
                {
                    throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
                }

                DSAParameters parameters = new DSAParameters();

                DerSequenceReader publicKeyReader =
                    Interop.AppleCrypto.SecKeyExport(keys.PublicKey, exportPrivate: false);

                publicKeyReader.ReadSubjectPublicKeyInfo(ref parameters);

                if (includePrivateParameters)
                {
                    DerSequenceReader privateKeyReader =
                        Interop.AppleCrypto.SecKeyExport(keys.PrivateKey, exportPrivate: true);

                    privateKeyReader.ReadPkcs8Blob(ref parameters);
                }

                KeyBlobHelpers.TrimPaddingByte(ref parameters.P);
                KeyBlobHelpers.TrimPaddingByte(ref parameters.Q);

                KeyBlobHelpers.PadOrTrim(ref parameters.G, parameters.P.Length);
                KeyBlobHelpers.PadOrTrim(ref parameters.Y, parameters.P.Length);

                if (includePrivateParameters)
                {
                    KeyBlobHelpers.PadOrTrim(ref parameters.X, parameters.Q.Length);
                }

                return(parameters);
            }
        /// <summary>
        /// Exports the DSAParameters.
        /// </summary>
        /// <param name="includePrivateParameters">true to include the private key; otherwise, false.</param>
        /// <returns>The parameters for DSA.</returns>
        public DSAParameters ExportParameters(bool includePrivateParameters)
        {
            DSAParameters parms = new DSAParameters();

            int keySizeBytes = KeySizeValue / 8;
            int cntAttribs   = includePrivateParameters ? 5 : 4;

            parms.P = new byte[keySizeBytes];
            parms.Q = new byte[160 / 8];
            parms.G = new byte[keySizeBytes];
            parms.Y = new byte[keySizeBytes];

            if (includePrivateParameters)
            {
                parms.X = new byte[160 / 8];
            }


            CryptokiAttribute[] attribs = new CryptokiAttribute[cntAttribs];

            attribs[0] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.Prime, parms.P);
            attribs[1] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.Subprime, parms.Q);
            attribs[2] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.Base, parms.G);
            attribs[3] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.PublicExponent, parms.Y);

            if (includePrivateParameters)
            {
                attribs[4] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.PrivateExponent, parms.X);
            }

            if (!KeyPair.GetAttributeValues(ref attribs))
            {
                throw new CryptographicException();
            }

            return(parms);
        }
Beispiel #38
0
        /// <summary>Reconstructs a <see cref="T:System.Security.Cryptography.DSA" /> object from an XML string.</summary>
        /// <param name="xmlString">The XML string to use to reconstruct the <see cref="T:System.Security.Cryptography.DSA" /> object. </param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="xmlString" /> parameter is null. </exception>
        /// <exception cref="T:System.Security.Cryptography.CryptographicException">The format of the <paramref name="xmlString" /> parameter is not valid. </exception>
        public override void FromXmlString(string xmlString)
        {
            if (xmlString == null)
            {
                throw new ArgumentNullException("xmlString");
            }
            DSAParameters parameters = default(DSAParameters);

            try
            {
                parameters.P    = AsymmetricAlgorithm.GetNamedParam(xmlString, "P");
                parameters.Q    = AsymmetricAlgorithm.GetNamedParam(xmlString, "Q");
                parameters.G    = AsymmetricAlgorithm.GetNamedParam(xmlString, "G");
                parameters.J    = AsymmetricAlgorithm.GetNamedParam(xmlString, "J");
                parameters.Y    = AsymmetricAlgorithm.GetNamedParam(xmlString, "Y");
                parameters.X    = AsymmetricAlgorithm.GetNamedParam(xmlString, "X");
                parameters.Seed = AsymmetricAlgorithm.GetNamedParam(xmlString, "Seed");
                byte[] namedParam = AsymmetricAlgorithm.GetNamedParam(xmlString, "PgenCounter");
                if (namedParam != null)
                {
                    byte[] array = new byte[4];
                    Buffer.BlockCopy(namedParam, 0, array, 0, namedParam.Length);
                    parameters.Counter = BitConverterLE.ToInt32(array, 0);
                }
                this.ImportParameters(parameters);
            }
            catch
            {
                this.ZeroizePrivateKey(parameters);
                throw;
            }
            finally
            {
                this.ZeroizePrivateKey(parameters);
            }
        }
        //
        // public methods
        //

        /// <summary>
        /// Imports the specified DSAParameters.
        /// </summary>
        /// <param name="parameters">The parameters for DSA.</param>
        public void ImportParameters(DSAParameters parameters)
        {
            bool fIncludePrivate = parameters.X != null;
            int  cntAttribs      = fIncludePrivate ? 7 : 6;

            CryptokiAttribute[] attribs = new CryptokiAttribute[cntAttribs];

            attribs[0] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class,
                                               Utility.ConvertToBytes((int)(fIncludePrivate ? CryptokiClass.PRIVATE_KEY : CryptokiClass.PUBLIC_KEY)));
            attribs[1] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.KeyType,
                                               Utility.ConvertToBytes((int)CryptoKey.KeyType.DSA));
            attribs[2] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.Prime, parameters.P);
            attribs[3] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.Subprime, parameters.Q);
            attribs[4] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.Base, parameters.G);
            attribs[5] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.PublicExponent, parameters.Y);

            if (fIncludePrivate)
            {
                attribs[6] = new CryptokiAttribute(CryptokiAttribute.CryptokiType.PrivateExponent, parameters.X);
            }

            KeyPair     = CryptoKey.LoadKey(m_session, attribs);
            OwnsKeyPair = true;
        }
Beispiel #40
0
        private unsafe AsnWriter WritePkcs8()
        {
            DSAParameters dsaParameters = ExportParameters(true);

            fixed(byte *privPin = dsaParameters.X)
            {
                try
                {
                    AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);

                    writer.PushSequence();
                    writer.WriteInteger(0);
                    WriteAlgorithmId(writer, dsaParameters);
                    WriteKeyComponent(writer, dsaParameters.X, bitString: false);
                    writer.PopSequence();

                    return(writer);
                }
                finally
                {
                    CryptographicOperations.ZeroMemory(dsaParameters.X);
                }
            }
        }
Beispiel #41
0
        public byte[] ExportCspBlob(bool includePrivateParameters)
        {
            DSAParameters parameters = ExportParameters(includePrivateParameters);

            return(parameters.ToKeyBlob());
        }
Beispiel #42
0
        private static void GenerateV2DsaBlob(BinaryWriter bw, DSAParameters parameters, int keySizeInBytes, bool hasPrivateKey)
        {
            // Write out a BCRYPT_DSA_KEY_BLOB_V2
            bw.Write((int)(hasPrivateKey ? KeyBlobMagicNumber.DsaPrivateV2 : KeyBlobMagicNumber.DsaPublicV2));
            bw.Write((int)keySizeInBytes);

            //
            // For some reason, Windows bakes the hash algorithm into the key itself. Furthermore, it demands that the Q length match the
            // length of the named hash algorithm's output - otherwise, the Import fails. So we have to give it the hash algorithm that matches
            // the Q length - and if there is no matching hash algorithm, we throw up our hands and throw a PlatformNotSupported.
            //
            // Note that this has no bearing on the hash algorithm you pass to SignData(). The class library (not Windows) hashes that according
            // to the hash algorithm passed to SignData() and presents the hash result to NCryptSignHash(), truncating the hash to the Q length
            // if necessary (and as demanded by the NIST spec.) Windows will be no wiser and we'll get the result we want.
            //
            HASHALGORITHM_ENUM hashAlgorithm;

            switch (parameters.Q.Length)
            {
            case Sha1HashOutputSize:
                hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA1;
                break;

            case Sha256HashOutputSize:
                hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA256;
                break;

            case Sha512HashOutputSize:
                hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA512;
                break;

            default:
                throw new PlatformNotSupportedException(SR.Cryptography_InvalidDsaParameters_QRestriction_LargeKey);
            }
            bw.Write((int)hashAlgorithm);

            bw.Write((int)(DSAFIPSVERSION_ENUM.DSA_FIPS186_3));

            if (parameters.Seed != null)
            {
                bw.Write((int)(parameters.Seed.Length)); //cbSeedLength
                bw.Write((int)(parameters.Q.Length));    //cbGroupLength (the Q length)

                bw.Write((byte[])ToBigEndian(parameters.Counter));
                bw.Write(parameters.Seed);
            }
            else
            {
                // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject
                // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng.

                int defaultSeedLength = parameters.Q.Length;

                bw.Write((int)(defaultSeedLength));   //cbSeedLength
                bw.Write((int)(parameters.Q.Length)); //cbGroupLength (the Q length)

                bw.Write((uint)0xffffffff);
                for (int i = 0; i < defaultSeedLength; i++)
                {
                    bw.Write((byte)0xff);
                }
            }

            bw.Write(parameters.Q);
            bw.Write(parameters.P);
            bw.Write(parameters.G);
            bw.Write(parameters.Y);
            if (hasPrivateKey)
            {
                bw.Write(parameters.X);
            }
        }
        /// <include file='doc\DSACryptoServiceProvider.uex' path='docs/doc[@for="DSACryptoServiceProvider.ImportParameters"]/*' />
        public override void ImportParameters(DSAParameters parameters)
        {
            if (_CSPHandleProtector.IsClosed || _KeyHandleProtector.IsClosed)
            {
                throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1"));
            }

            DSACspObject dsaKey = new DSACspObject();

            // P, Q, G are required
            if (parameters.P == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_MissingField"));
            }
            dsaKey.P = (byte[])parameters.P.Clone();
            if (parameters.Q == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_MissingField"));
            }
            dsaKey.Q = (byte[])parameters.Q.Clone();
            if (parameters.G == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_MissingField"));
            }
            dsaKey.G = (byte[])parameters.G.Clone();

            //  Y is not required
            dsaKey.Y = (parameters.Y == null ? null : ((byte[])parameters.Y.Clone()));
            //  J is not required
            dsaKey.J = (parameters.J == null ? null : ((byte[])parameters.J.Clone()));

            //  seed is not required
            dsaKey.seed = (parameters.Seed == null ? null : ((byte[])parameters.Seed.Clone()));
            //  counter is not required
            dsaKey.counter = parameters.Counter;
            //  X is not required -- private component
            dsaKey.X = (parameters.X == null ? null : ((byte[])parameters.X.Clone()));

            // NOTE: We must reverse the dsaKey before importing!
            ReverseDSACspObject(dsaKey);
            // Free the current key handle
            _KeyHandleProtector.Close();
            // Now, import the key into the CSP
            bool incremented = false;

            try {
                if (_CSPHandleProtector.TryAddRef(ref incremented))
                {
                    _hKey = _ImportKey(_CSPHandleProtector.Handle, CALG_DSA_SIGN, dsaKey);
                }
                else
                {
                    throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1"));
                }
            }
            finally {
                if (incremented)
                {
                    _CSPHandleProtector.Release();
                }
            }

            _KeyHandleProtector   = new __KeyHandleProtector(_hKey);
            _parameters.KeyNumber = AT_SIGNATURE;
            if (dsaKey.X == null)
            {
                // If no X, then only have the public
                _containerContents = KeyContainerContents.PublicOnly;
            }
            else
            {
                // Our key pairs are always exportable
                _containerContents = KeyContainerContents.PublicAndExportablePrivate;
            }
            // zeroize private key material
            if (dsaKey.X != null)
            {
                Array.Clear(dsaKey.X, 0, dsaKey.X.Length);
            }
        }
        /************************* PUBLIC METHODS ************************/

        /// <include file='doc\DSACryptoServiceProvider.uex' path='docs/doc[@for="DSACryptoServiceProvider.ExportParameters"]/*' />
        public override DSAParameters ExportParameters(bool includePrivateParameters)
        {
            int hr;

            if (_CSPHandleProtector.IsClosed || _KeyHandleProtector.IsClosed)
            {
                throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1"));
            }

            DSACspObject  dsaKey    = new DSACspObject();
            DSAParameters dsaParams = new DSAParameters();

            if (includePrivateParameters)
            {
                bool incremented = false;
                try {
                    if (_KeyHandleProtector.TryAddRef(ref incremented))
                    {
                        hr = _ExportKey(_KeyHandleProtector.Handle, PRIVATEKEYBLOB, dsaKey);
                    }
                    else
                    {
                        throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1"));
                    }
                }
                finally {
                    if (incremented)
                    {
                        _KeyHandleProtector.Release();
                    }
                }
                if (hr != 0)
                {
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_ExportKey"));
                }
                // Must reverse after export from CAPI!
                ReverseDSACspObject(dsaKey);
                dsaParams.P = dsaKey.P;
                dsaParams.Q = dsaKey.Q;
                dsaParams.G = dsaKey.G;
                dsaParams.Y = dsaKey.Y;
                dsaParams.X = dsaKey.X;
                if (dsaKey.J != null)
                {
                    dsaParams.J = dsaKey.J;
                }
                if (dsaKey.seed != null)
                {
                    dsaParams.Seed    = dsaKey.seed;
                    dsaParams.Counter = dsaKey.counter;
                }
            }
            else
            {
                bool incremented = false;
                try {
                    if (_KeyHandleProtector.TryAddRef(ref incremented))
                    {
                        hr = _ExportKey(_KeyHandleProtector.Handle, PUBLICKEYBLOB, dsaKey);
                    }
                    else
                    {
                        throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic_ObjectName1"));
                    }
                }
                finally {
                    if (incremented)
                    {
                        _KeyHandleProtector.Release();
                    }
                }
                if (hr != 0)
                {
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_ExportKey"));
                }
                // Must reverse (into network byte order) after export from CAPI!
                ReverseDSACspObject(dsaKey);
                dsaParams.P = dsaKey.P;
                dsaParams.Q = dsaKey.Q;
                dsaParams.G = dsaKey.G;
                dsaParams.Y = dsaKey.Y;
                if (dsaKey.J != null)
                {
                    dsaParams.J = dsaKey.J;
                }
                if (dsaKey.seed != null)
                {
                    dsaParams.Seed    = dsaKey.seed;
                    dsaParams.Counter = dsaKey.counter;
                }
                // zeroize private key material
                if (dsaKey.X != null)
                {
                    Array.Clear(dsaKey.X, 0, dsaKey.X.Length);
                }
            }
            return(dsaParams);
        }
Beispiel #45
0
		static public DSA FromCapiPublicKeyBlobDSA (byte[] blob, int offset)
		{
			if (blob == null)
				throw new ArgumentNullException ("blob");
			if (offset >= blob.Length)
				throw new ArgumentException ("blob is too small.");

			try {
				if ((blob [offset] != 0x06) ||				// PUBLICKEYBLOB (0x06)
				    (blob [offset + 1] != 0x02) ||			// Version (0x02)
				    (blob [offset + 2] != 0x00) ||			// Reserved (word)
				    (blob [offset + 3] != 0x00) ||
				    (ToUInt32LE (blob, offset + 8) != 0x31535344))	// DWORD magic
					throw new CryptographicException ("Invalid blob header");

				int bitlen = ToInt32LE (blob, offset + 12);
				DSAParameters dsap = new DSAParameters ();
				int bytelen = bitlen >> 3;
				int pos = offset + 16;

				dsap.P = new byte [bytelen];
				Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
				Array.Reverse (dsap.P);
				pos += bytelen;

				dsap.Q = new byte [20];
				Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
				Array.Reverse (dsap.Q);
				pos += 20;

				dsap.G = new byte [bytelen];
				Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
				Array.Reverse (dsap.G);
				pos += bytelen;

				dsap.Y = new byte [bytelen];
				Buffer.BlockCopy (blob, pos, dsap.Y, 0, bytelen);
				Array.Reverse (dsap.Y);
				pos += bytelen;

				dsap.Counter = ToInt32LE (blob, pos);
				pos += 4;

				dsap.Seed = new byte [20];
				Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
				Array.Reverse (dsap.Seed);
				pos += 20;

				DSA dsa = (DSA)DSA.Create ();
				dsa.ImportParameters (dsap);
				return dsa;
			}
			catch (Exception e) {
				throw new CryptographicException ("Invalid blob.", e);
			}
		}
Beispiel #46
0
        public override string ToXmlString(bool includePrivateParameters)
        {
            // The format of this output is based on the xmldsig ds:DSAKeyValue value, except
            // * It writes values as xml:base64Binary instead of ds:CryptoBinary
            //   * It doesn't strip off leading 0x00 byte values before base64
            // * It doesn't emit the output in a namespace
            // * When includePrivateParameters is true it writes an X element.
            //
            // These deviations are inherited from .NET Framework.

            // P is KeySizeInBytes long.
            // Q is 160 to 256 bits long, or 20 to 32 bytes.
            // G is the same size as P
            // Y is the same size as P
            // X is the same size as Q
            //
            // Each field gets base64 encoded (after dropping leading 0x00 bytes)
            // so P is (KeySizeInBytes + 2) / 3 * 4, then plus 7 (<P></P>)
            // (For 3072 that's 519 chars, for 1024 it's 179.)
            // Add in maximum-Q: (32 + 2) / 3 * 4 + 7 => 51
            // Then the "<DSAKeyValue></DSAKeyValue>" (27).
            // Grand total, 3 * P + 2 * Q + 27 => 1686 (3072) or 666 (1024).
            // KeySizeInBytes * 2 / 3 comes out to 2048 or 682, so call that good enough.

            // Rarely, keys will export the J or Seed values, and they may cause the
            // StringBuilder to need to grow.

            DSAParameters keyParameters = ExportParameters(includePrivateParameters);
            StringBuilder builder       = new StringBuilder((keyParameters.P.Length << 1) / 3);

            builder.Append("<DSAKeyValue>");
            XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.P), keyParameters.P, builder);
            XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.Q), keyParameters.Q, builder);
            XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.G), keyParameters.G, builder);
            XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.Y), keyParameters.Y, builder);

            if (keyParameters.J != null)
            {
                XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.J), keyParameters.J, builder);
            }

            if (keyParameters.Seed != null)
            {
                XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.Seed), keyParameters.Seed, builder);
                XmlKeyHelper.WriteCryptoBinary(CounterElementName, keyParameters.Counter, builder);
            }

            if (includePrivateParameters)
            {
                if (keyParameters.X == null)
                {
                    // NetFx compat when a 3rd party type lets X be null when
                    // includePrivateParameters is true
                    // (the exception would have been from Convert.ToBase64String)
                    throw new ArgumentNullException("inArray");
                }

                XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.X), keyParameters.X, builder);
            }

            builder.Append("</DSAKeyValue>");
            return(builder.ToString());
        }
Beispiel #47
0
        public void ImportCspBlob(byte[] keyBlob)
        {
            DSAParameters parameters = keyBlob.ToDSAParameters(!IsPublic(keyBlob), null);

            ImportParameters(parameters);
        }
Beispiel #48
0
 public abstract void ImportParameters(DSAParameters parameters);
Beispiel #49
0
            public override void ImportParameters(DSAParameters parameters)
            {
                if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null)
                {
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields);
                }

                // J is not required and is not even used on CNG blobs.
                // It should, however, be less than P (J == (P-1) / Q).
                // This validation check is just to maintain parity with DSACng and DSACryptoServiceProvider,
                // which also perform this check.
                if (parameters.J != null && parameters.J.Length >= parameters.P.Length)
                {
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ);
                }

                int  keySize       = parameters.P.Length;
                bool hasPrivateKey = parameters.X != null;

                if (parameters.G.Length != keySize || parameters.Y.Length != keySize)
                {
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);
                }

                if (hasPrivateKey && parameters.X.Length != parameters.Q.Length)
                {
                    throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);
                }

                if (!(8 * parameters.P.Length).IsLegalSize(LegalKeySizes))
                {
                    throw new CryptographicException(SR.Cryptography_InvalidKeySize);
                }

                if (parameters.Q.Length != 20)
                {
                    throw new CryptographicException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey);
                }

                if (hasPrivateKey)
                {
                    SafeSecKeyRefHandle privateKey = ImportKey(parameters);

                    DSAParameters publicOnly = parameters;
                    publicOnly.X = null;

                    SafeSecKeyRefHandle publicKey;
                    try
                    {
                        publicKey = ImportKey(publicOnly);
                    }
                    catch
                    {
                        privateKey.Dispose();
                        throw;
                    }

                    SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
                }
                else
                {
                    SafeSecKeyRefHandle publicKey = ImportKey(parameters);
                    SetKey(SecKeyPair.PublicOnly(publicKey));
                }
            }
        /// <summary>Reconstructs a <see cref="T:System.Security.Cryptography.DSA" /> object from an XML string.</summary>
        /// <param name="xmlString">The XML string to use to reconstruct the <see cref="T:System.Security.Cryptography.DSA" /> object. </param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="xmlString" /> parameter is <see langword="null" />. </exception>
        /// <exception cref="T:System.Security.Cryptography.CryptographicException">The format of the <paramref name="xmlString" /> parameter is not valid. </exception>
        // Token: 0x06002178 RID: 8568 RVA: 0x0007658C File Offset: 0x0007478C
        public override void FromXmlString(string xmlString)
        {
            if (xmlString == null)
            {
                throw new ArgumentNullException("xmlString");
            }
            DSAParameters   parameters = default(DSAParameters);
            Parser          parser     = new Parser(xmlString);
            SecurityElement topElement = parser.GetTopElement();
            string          text       = topElement.SearchForTextOfLocalName("P");

            if (text == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[]
                {
                    "DSA",
                    "P"
                }));
            }
            parameters.P = Convert.FromBase64String(Utils.DiscardWhiteSpaces(text));
            string text2 = topElement.SearchForTextOfLocalName("Q");

            if (text2 == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[]
                {
                    "DSA",
                    "Q"
                }));
            }
            parameters.Q = Convert.FromBase64String(Utils.DiscardWhiteSpaces(text2));
            string text3 = topElement.SearchForTextOfLocalName("G");

            if (text3 == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[]
                {
                    "DSA",
                    "G"
                }));
            }
            parameters.G = Convert.FromBase64String(Utils.DiscardWhiteSpaces(text3));
            string text4 = topElement.SearchForTextOfLocalName("Y");

            if (text4 == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[]
                {
                    "DSA",
                    "Y"
                }));
            }
            parameters.Y = Convert.FromBase64String(Utils.DiscardWhiteSpaces(text4));
            string text5 = topElement.SearchForTextOfLocalName("J");

            if (text5 != null)
            {
                parameters.J = Convert.FromBase64String(Utils.DiscardWhiteSpaces(text5));
            }
            string text6 = topElement.SearchForTextOfLocalName("X");

            if (text6 != null)
            {
                parameters.X = Convert.FromBase64String(Utils.DiscardWhiteSpaces(text6));
            }
            string text7 = topElement.SearchForTextOfLocalName("Seed");
            string text8 = topElement.SearchForTextOfLocalName("PgenCounter");

            if (text7 != null && text8 != null)
            {
                parameters.Seed    = Convert.FromBase64String(Utils.DiscardWhiteSpaces(text7));
                parameters.Counter = Utils.ConvertByteArrayToInt(Convert.FromBase64String(Utils.DiscardWhiteSpaces(text8)));
            }
            else if (text7 != null || text8 != null)
            {
                if (text7 == null)
                {
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[]
                    {
                        "DSA",
                        "Seed"
                    }));
                }
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", new object[]
                {
                    "DSA",
                    "PgenCounter"
                }));
            }
            this.ImportParameters(parameters);
        }
Beispiel #51
0
			// DSA only encode it's X private key inside an ASN.1 INTEGER (Hint: Tag == 0x02)
			// which isn't enough for rebuilding the keypair. The other parameters
			// can be found (98% of the time) in the X.509 certificate associated
			// with the private key or (2% of the time) the parameters are in it's
			// issuer X.509 certificate (not supported in the .NET framework).
			static public DSA DecodeDSA (byte[] privateKey, DSAParameters dsaParameters) 
			{
				ASN1 pvk = new ASN1 (privateKey);
				if (pvk.Tag != 0x02)
					throw new CryptographicException ("invalid private key format");

				// X is ALWAYS 20 bytes (no matter if the key length is 512 or 1024 bits)
				dsaParameters.X = Normalize (pvk.Value, 20);
				DSA dsa = DSA.Create ();
				dsa.ImportParameters (dsaParameters);
				return dsa;
			}
Beispiel #52
0
		public override void ImportParameters (DSAParameters parameters) 
		{
			dsa.ImportParameters (parameters);
		}
Beispiel #53
0
 private static bool IsPublic(DSAParameters dsaParams)
 {
     return(dsaParams.X == null);
 }
Beispiel #54
0
		static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob, int offset)
		{
			if (blob == null)
				throw new ArgumentNullException ("blob");
			if (offset >= blob.Length)
				throw new ArgumentException ("blob is too small.");

			DSAParameters dsap = new DSAParameters ();
			try {
				if ((blob [offset] != 0x07) ||				// PRIVATEKEYBLOB (0x07)
				    (blob [offset + 1] != 0x02) ||			// Version (0x02)
				    (blob [offset + 2] != 0x00) ||			// Reserved (word)
				    (blob [offset + 3] != 0x00) ||
				    (ToUInt32LE (blob, offset + 8) != 0x32535344))	// DWORD magic
					throw new CryptographicException ("Invalid blob header");

				int bitlen = ToInt32LE (blob, offset + 12);
				int bytelen = bitlen >> 3;
				int pos = offset + 16;

				dsap.P = new byte [bytelen];
				Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
				Array.Reverse (dsap.P);
				pos += bytelen;

				dsap.Q = new byte [20];
				Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
				Array.Reverse (dsap.Q);
				pos += 20;

				dsap.G = new byte [bytelen];
				Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
				Array.Reverse (dsap.G);
				pos += bytelen;

				dsap.X = new byte [20];
				Buffer.BlockCopy (blob, pos, dsap.X, 0, 20);
				Array.Reverse (dsap.X);
				pos += 20;

				dsap.Counter = ToInt32LE (blob, pos);
				pos += 4;

				dsap.Seed = new byte [20];
				Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
				Array.Reverse (dsap.Seed);
				pos += 20;
			}
			catch (Exception e) {
				throw new CryptographicException ("Invalid blob.", e);
			}

#if INSIDE_CORLIB && MOBILE
			DSA dsa = (DSA)DSA.Create ();
			dsa.ImportParameters (dsap);
#else
			DSA dsa = null;
			try {
				dsa = (DSA)DSA.Create ();
				dsa.ImportParameters (dsap);
			}
			catch (CryptographicException ce) {
				// this may cause problem when this code is run under
				// the SYSTEM identity on Windows (e.g. ASP.NET). See
				// http://bugzilla.ximian.com/show_bug.cgi?id=77559
				try {
					CspParameters csp = new CspParameters ();
					csp.Flags = CspProviderFlags.UseMachineKeyStore;
					dsa = new DSACryptoServiceProvider (csp);
					dsa.ImportParameters (dsap);
				}
				catch {
					// rethrow original, not the later, exception if this fails
					throw ce;
				}
			}
#endif
			return dsa;
		}
Beispiel #55
0
 public override void ImportParameters(DSAParameters parameters)
 {
     throw new NotImplementedException();
 }
 public override void ImportParameters(DSAParameters parameters)
 {
     byte[] keyBlob = parameters.ToKeyBlob();
     ImportCspBlob(keyBlob);
 }
Beispiel #57
0
        internal static void ReadSubjectPublicKeyInfo(this DerSequenceReader keyInfo, ref DSAParameters parameters)
        {
            // SubjectPublicKeyInfo::= SEQUENCE  {
            //    algorithm AlgorithmIdentifier,
            //    subjectPublicKey     BIT STRING  }
            DerSequenceReader algorithm    = keyInfo.ReadSequence();
            string            algorithmOid = algorithm.ReadOidAsString();

            // EC Public Key
            if (algorithmOid != s_idDsa.Value)
            {
                throw new CryptographicException();
            }

            // Dss-Parms ::= SEQUENCE {
            //   p INTEGER,
            //   q INTEGER,
            //   g INTEGER
            // }

            DerSequenceReader algParameters = algorithm.ReadSequence();

            byte[] publicKeyBlob = keyInfo.ReadBitString();
            // We don't care about the rest of the blob here, but it's expected to not exist.

            ReadSubjectPublicKeyInfo(algParameters, publicKeyBlob, ref parameters);
        }
Beispiel #58
0
        private static void WriteDSSSeed(DSAParameters dsaParameters, BinaryWriter bw)
        {
            if (dsaParameters.Seed == null || dsaParameters.Seed.Length == 0)
            {
                bw.Write(0xFFFFFFFF); // counter

                // seed[20] needs to be all 0xFF
                for (int i = 0; i < 20; i += sizeof(uint))
                {
                    bw.Write(0xFFFFFFFF);
                }
            }
            else
            {
                bw.Write((int)dsaParameters.Counter);
                bw.WriteReversed(dsaParameters.Seed);
            }
        }
		public DSAParameters ParseDSAPrivateKey()
		{
			var parameters = new DSAParameters();

			// Current value
			byte[] value = null;

			// Current Position
			int position = parser.CurrentPosition();
			// Sanity Checks
			int length = 0;

			// Ignore Sequence - PrivateKeyInfo
			length = parser.NextSequence();
			if (length != parser.RemainingBytes())
			{
				var sb = new StringBuilder("Incorrect Sequence Size. ");
				sb.AppendFormat("Specified: {0}, Remaining: {1}",
				                length.ToString(CultureInfo.InvariantCulture),
				                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
				throw new BerDecodeException(sb.ToString(), position);
			}

			// Checkpoint
			position = parser.CurrentPosition();
			// Version
			value = parser.NextInteger();
			if (0x00 != value[0])
			{
				throw new BerDecodeException("Incorrect PrivateKeyInfo Version", position);
			}

			// Checkpoint
			position = parser.CurrentPosition();

			// Ignore Sequence - AlgorithmIdentifier
			length = parser.NextSequence();
			if (length > parser.RemainingBytes())
			{
				var sb = new StringBuilder("Incorrect AlgorithmIdentifier Size. ");
				sb.AppendFormat("Specified: {0}, Remaining: {1}",
				                length.ToString(CultureInfo.InvariantCulture),
				                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
				throw new BerDecodeException(sb.ToString(), position);
			}

			// Checkpoint
			position = parser.CurrentPosition();
			// Grab the OID
			value = parser.NextOID();
			byte[] oid = {0x2a, 0x86, 0x48, 0xce, 0x38, 0x04, 0x01};
			if (!EqualOid(value, oid))
			{
				throw new BerDecodeException("Expected OID 1.2.840.10040.4.1", position);
			}

			// Checkpoint
			position = parser.CurrentPosition();

			// Ignore Sequence - DSS-Params
			length = parser.NextSequence();
			if (length > parser.RemainingBytes())
			{
				var sb = new StringBuilder("Incorrect DSS-Params Size. ");
				sb.AppendFormat("Specified: {0}, Remaining: {1}",
				                length.ToString(CultureInfo.InvariantCulture),
				                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
				throw new BerDecodeException(sb.ToString(), position);
			}

			// Next three are curve parameters
			parameters.P = TrimLeadingZero(parser.NextInteger());
			parameters.Q = TrimLeadingZero(parser.NextInteger());
			parameters.G = TrimLeadingZero(parser.NextInteger());

			// Ignore OctetString - PrivateKey
			parser.NextOctetString();

			// Private Key
			parameters.X = TrimLeadingZero(parser.NextInteger());

			Debug.Assert(0 == parser.RemainingBytes());

			return parameters;
		}
 public override void ImportParameters(DSAParameters parameters)
 {
 }