SignData() public méthode

Computes the hash value of the specified input stream and signs the resulting hash value.
public SignData ( Stream inputStream ) : byte[]
inputStream Stream The input data for which to compute the hash.
Résultat byte[]
        public void TestMethodSendPrivateMessage()
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            DSACryptoServiceProvider mycryptoC = new DSACryptoServiceProvider();
            DSAParameters publickeyC = mycryptoC.ExportParameters(false);

            DSACryptoServiceProvider mycryptoW = new DSACryptoServiceProvider();
            DSAParameters publickeyW = mycryptoW.ExportParameters(false);

            byte[] hashC = mycryptoC.SignData(encoding.GetBytes("Cuddy"));
            byte[] hashW = mycryptoW.SignData(encoding.GetBytes("Wilson"));

            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            a.Register("Cuddy", "iluvhouse", hashC, publickeyC.Counter, publickeyC.G, publickeyC.J, publickeyC.P, publickeyC.Q, publickeyC.Seed, publickeyC.X, publickeyC.Y);
            a.Register("Wilson", "ihatehouse", hashW, publickeyW.Counter, publickeyW.G, publickeyW.J, publickeyW.P, publickeyW.Q, publickeyW.Seed, publickeyW.X, publickeyW.Y);

            string message = "je suis jalouse de Cameron";
            byte[] messagesigned = mycryptoC.SignData(encoding.GetBytes(message));

            Assert.AreEqual(true,a.SendPrivateMessage("Cuddy", "Wilson", message, messagesigned));
            Assert.AreEqual(false, a.SendPrivateMessage("Cuddy", "Foreman", message, messagesigned));

            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
        }
        public void TestMethodReceivePrivateMessage()
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            DSACryptoServiceProvider mycryptoC = new DSACryptoServiceProvider();
            DSAParameters publickeyC = mycryptoC.ExportParameters(false);

            DSACryptoServiceProvider mycryptoW = new DSACryptoServiceProvider();
            DSAParameters publickeyW = mycryptoW.ExportParameters(false);

            byte[] hashC = mycryptoC.SignData(encoding.GetBytes("Cuddy"));
            byte[] hashW = mycryptoW.SignData(encoding.GetBytes("Wilson"));

            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            a.Register("Cuddy", "iluvhouse", hashC, publickeyC.Counter, publickeyC.G, publickeyC.J, publickeyC.P, publickeyC.Q, publickeyC.Seed, publickeyC.X, publickeyC.Y);
            a.Register("Wilson", "ihatehouse", hashW, publickeyW.Counter, publickeyW.G, publickeyW.J, publickeyW.P, publickeyW.Q, publickeyW.Seed, publickeyW.X, publickeyW.Y);

            string message = "je suis jalouse de Cameron";
            byte[] messagesigned = mycryptoC.SignData(encoding.GetBytes(message));

            a.SendPrivateMessage("Cuddy", "Wilson", message, messagesigned);
            UnitTest.ServiceReference1.Message[] b = a.ReceivePrivateMessage("Wilson", hashW);

            Assert.AreEqual("Cuddy", b[0].Auteur); //j'avoue les test sont moisi... mais je voulais juste verifier si le retour par une classe implemente dans le webservice etait possible
            Assert.AreEqual("je suis jalouse de Cameron", b[0].Text);

            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
        }
        public void TestMethodCHangeNick()
        {
            DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider();
            DSAParameters Publickey = mycrypto.ExportParameters(false);
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] hash = mycrypto.SignData(encoding.GetBytes("Cuddy"));
            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            a.Register("Cuddy", "passbidon", hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y);
            Assert.AreEqual(true, a.ChangeNick("Cuddy", "MissC", mycrypto.SignData(encoding.GetBytes("MissC"))));
            hash = mycrypto.SignData(encoding.GetBytes("MissC"));
            Assert.AreEqual(true, a.LogIn("MissC", "passbidon", hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y));
        }
Exemple #4
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);
        }
Exemple #5
0
 /// <summary>
 /// DSA 加密
 /// </summary>
 /// <param name="password">要加密的字符串</param>
 /// <returns>等效于此实例经过 DSA 加密密文</returns>
 public static string DSAEncryptPassword(string password)
 {
     if (password == null)
     {
         throw new ArgumentNullException("password");
     }
     DSACryptoServiceProvider ServiceProvider = new DSACryptoServiceProvider();
     string NewPassword = BitConverter.ToString(ServiceProvider.SignData(Encoding.UTF8.GetBytes(password)));
     ServiceProvider.Clear();
     return NewPassword.Replace("-", null);
 }
        public void TestMethodReceiveAllMessage()
        {
            DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider();
            DSAParameters publickey = mycrypto.ExportParameters(false);

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] hash = mycrypto.SignData(encoding.GetBytes("Cuddy"));
            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            string message = "je suis jalouse de Cameron";
            byte[] messagesigned = mycrypto.SignData(encoding.GetBytes(message));
            a.Register("Cuddy", "iluvhouse", hash, publickey.Counter, publickey.G, publickey.J, publickey.P, publickey.Q, publickey.Seed, publickey.X, publickey.Y);
            a.SendMessage("Cuddy", message, messagesigned);

            UnitTest.ServiceReference1.Message[] b = a.ReceiveMessageNonRead("Cuddy", hash);
            UnitTest.ServiceReference1.Message[] c = a.ReceiveAllMessage("Cuddy", hash);

            Assert.AreEqual("je suis jalouse de Cameron", c[0].Text); //identique a tous les reception de message[]
            Assert.AreEqual("Cuddy", c[0].Auteur);
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
        }
Exemple #7
0
        public static byte[] Sign(byte[] data, byte[] signKeyPair)
        {
            using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider())
            {
                dsa.ImportCspBlob(signKeyPair);

                if (dsa.PublicOnly)
                {
                    throw new InvalidOperationException("You must have both the public and private key");
                }

                return dsa.SignData(data);
            }
        }
        public static string CreateSignature(string inputData, String privateKey)
        {
            // create the crypto-service provider:
            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();

            // setup the dsa from the private key:
            dsa.FromXmlString(privateKey);

            byte[] data = UTF8Encoding.ASCII.GetBytes(inputData);

            // get the signature:
            byte[] signature = dsa.SignData(data);

            return Convert.ToBase64String(signature);
        }
        public void TestMethodSendMessage()
        {
            DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider();
            DSAParameters publickey = mycrypto.ExportParameters(false);
            DSACryptoServiceProvider petitmalin = new DSACryptoServiceProvider();
            DSAParameters Clemoisi = petitmalin.ExportParameters(false);

            ASCIIEncoding encoding = new ASCIIEncoding();
            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            byte[] hash = mycrypto.SignData(encoding.GetBytes("Cuddy"));
            string message = "je suis jalouse de Cameron";

            a.Register("Cuddy", "iluvhouse", hash, publickey.Counter, publickey.G, publickey.J, publickey.P, publickey.Q, publickey.Seed, publickey.X, publickey.Y);

            byte[] messagesigned = mycrypto.SignData(encoding.GetBytes(message));
            Assert.AreEqual(true, a.SendMessage("Cuddy", message, messagesigned));

            byte[] hashmoisi = petitmalin.SignData(encoding.GetBytes(message));
            Assert.AreEqual(false, a.SendMessage("Cuddy",message,hashmoisi));

            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
        }
Exemple #10
0
        public void TestMethodRegisterAndLogin()
        {
            DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider();
            DSAParameters Publickey = mycrypto.ExportParameters(false);
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] hash = mycrypto.SignData(encoding.GetBytes("Cuddy"));
            ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();

            Assert.AreEqual(true, a.Register("Cuddy", "passbidon",hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y));
            Assert.AreEqual(false, a.Register("Cuddy", "rate",hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y));

            Assert.AreEqual(true,a.LogIn("Cuddy", "passbidon",hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y));
            Assert.AreEqual(false, a.LogIn("Cuddy", "badpass",hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y));

            //remise a zero du serveur
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
            File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
        }
Exemple #11
0
        MFTestResults Test_ImportKey(Session session)
        {
            bool testResult = false;

            try
            {
                using (CryptoKey pubkey = CryptoKey.LoadKey(session, m_publicDsaKey))
                {
                    // replace publickey with private
                    CryptokiAttribute[] privateKey = new CryptokiAttribute[m_publicDsaKey.Length];

                    for (int x = 0; x < m_publicDsaKey.Length; x++)
                    {
                        privateKey[x] = new CryptokiAttribute(m_publicDsaKey[x].Type, new byte[m_publicDsaKey[x].Value.Length]);
                        Array.Copy(m_publicDsaKey[x].Value, privateKey[x].Value, m_publicDsaKey[x].Value.Length);
                    }

                    privateKey[0].Value = Utility.ConvertToBytes((int)CryptokiClass.PRIVATE_KEY);
                    privateKey[5].Value = new byte[]
                    {
                        0x45, 0xB3, 0x34, 0x77, 0x54, 0x3E, 0x7E, 0xBC, 0x82, 0xA8, 0x4E, 0x8E, 0x91, 0x55, 0x86, 0xC1, 
                        0xDA, 0x22, 0xDE, 0x09, 
                    };

                    using (CryptoKey privkey = CryptoKey.LoadKey(session, privateKey))
                    {
                        string dataToSign = "This is a simple message to be encrypted";

                        byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToSign);

                        using (DSACryptoServiceProvider dsaEncr = new DSACryptoServiceProvider(privkey))
                        using(DSACryptoServiceProvider dsaDecr = new DSACryptoServiceProvider(pubkey))
                        {
                            byte[] signature = dsaEncr.SignData(data);

                            testResult = dsaDecr.VerifyData(data, signature);
                        }
                    }

                    using (CryptoKey privkey = CryptoKey.LoadKey(session, m_privateDsaKey))
                    {
                        string dataToSign = "This is a simple message to be encrypted";

                        byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToSign);

                        using (DSACryptoServiceProvider dsaEncr = new DSACryptoServiceProvider(privkey))
                        using(DSACryptoServiceProvider dsaDecr = new DSACryptoServiceProvider(privkey))
                        {
                            byte[] signature = dsaEncr.SignData(data);

                            testResult &= dsaDecr.VerifyData(data, signature);
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected Exception", ex);
                testResult = false;
            }

            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
Exemple #12
0
        MFTestResults TestSignature(DSACryptoServiceProvider csp, HashAlgorithm hashAlg)
        {
            bool testResult = false;

            try
            {
                string dataToSign = "This is a simple message to be encrypted";

                byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToSign);

                byte[] signature = csp.SignData(data);

                testResult = csp.VerifyData(data, signature);

                byte[] hash = hashAlg.ComputeHash(data);

                signature = csp.SignHash(hash, hashAlg.HashType);
                testResult &= csp.VerifyHash(hash, hashAlg.HashType, signature);
            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected Exception", ex);
                testResult = false;
            }

            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
Exemple #13
0
        public MFTestResults DsaTest_ImportRsaKeyAndUseWithDsaShouldFail()
        {
            bool testResult = false;

            try
            {
                using (Session session = new Session("", MechanismType.DSA))
                using (CryptoKey obj = CryptokiObject.CreateObject(session, m_privateRsaKey) as CryptoKey)
                {
                    string dataToSign = "This is a simple message to be encrypted";

                    byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToSign);

                    using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(obj))
                    {
                        byte[] signature = dsa.SignData(data);

                        dsa.VerifyData(data, signature);
                    }
                }
            }
            catch (ArgumentException)
            {
                testResult = true;
            }
            catch
            {
                testResult = false;
            }

            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
        public static Boolean Test(int keySize)
        {
            Boolean bRes = true;
            Byte[] abData = new Byte[65536];
            Byte[] abSignature = null;
            Byte[] abSignature1 = null;
            int ks = keySize;

            for (int i = 0; i < 65536; i++) abData[i] = (Byte)(i % 256);

            try
            {
                using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(ks))
                {
                    abSignature = dsa.SignData(abData);
                    abSignature1 = dsa.SignData(abData);
                    /*          if(!Compare(abSignature, abSignature1)) {
                                    Log.Comment("WRONG : two signing passes gave different signatures!");
                                    bRes = false;
                                } */
                    Log.Comment("Signature is : ");
                    PrintByteArray(abSignature);

                    if (dsa.VerifyData(abData, abSignature))
                    {
                        Log.Comment("CORRECT : Signature OK");
                    }
                    else
                    {
                        Log.Comment("WRONG : Signature is BAD");
                        bRes = false;
                    }

                    if (dsa.VerifyData(abData, abSignature1))
                    {
                        Log.Comment("CORRECT : Signature1 OK");
                    }
                    else
                    {
                        Log.Comment("WRONG : Signature1 is BAD");
                        bRes = false;
                    }

                    abData[2]++;
                    if (dsa.VerifyData(abData, abSignature))
                    {
                        Log.Comment("WRONG : Signature OK");
                        bRes = false;
                    }
                    else
                    {
                        Log.Comment("CORRECT : Signature is BAD");
                    }

                    abData[2]--;
                    abSignature[1]++;
                    if (dsa.VerifyData(abData, abSignature))
                    {
                        Log.Comment("WRONG : Signature OK");
                        bRes = false;
                    }
                    else
                    {
                        Log.Comment("CORRECT : Signature is BAD");
                    }

                    abData[2]++;
                    if (dsa.VerifyData(abData, abSignature1))
                    {
                        Log.Comment("WRONG : Signature1 OK");
                        bRes = false;
                    }
                    else
                    {
                        Log.Comment("CORRECT : Signature1 is BAD");
                    }

                    abData[2]--;
                    abSignature1[1]++;
                    if (dsa.VerifyData(abData, abSignature1))
                    {
                        Log.Comment("WRONG : Signature1 OK");
                        bRes = false;
                    }
                    else
                    {
                        Log.Comment("CORRECT : Signature1 is BAD");
                    }
                }
            }
            catch (Exception e)
            {
                Log.Comment("Exception ocured :\n" + e.ToString());
                bRes = false;
            }

            return bRes;
        }
Exemple #15
0
        /// <summary>
        ///		Sign without private key
        /// </summary>
        private static void CSPSignNoPrivate()
        {
            //DSACryptoServiceProvider dsaPriv = new DSACryptoServiceProvider();
            //byte[] publicBlob = dsaPriv.ExportCspBlob(false);

            using (Session session = new Session("", MechanismType.DSA))
            {
                CryptoKey key = CryptoKey.CreateObject(session, m_publicDsaKey) as CryptoKey;

                using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(key))
                {
                    //dsa.ImportCspBlob(publicBlob);

                    dsa.SignData(new byte[] { 0, 1, 2, 3, 4, 5 });
                }
            }
        }
Exemple #16
0
        /// <summary>
        ///		Sign buffer
        /// </summary>
        private static bool CSPSignBuffer()
        {
            byte[] data = new byte[1025];
            for (int i = 2; i < data.Length; i++)
                data[i] = (byte)((data[i - 1] + data[i - 2]) % Byte.MaxValue);

            using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider())
            {
                byte[] sig = dsa.SignData(data, 25, 150);

                byte[] bufferPortion = new byte[150];
                Array.Copy(data, 25, bufferPortion, 0, 150);

                return dsa.VerifyData(bufferPortion, sig);
            }
        }
	private void SignAndVerify (string msg, DSACryptoServiceProvider dsa)
	{
		byte[] hash = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 };
		byte[] sign1 = dsa.CreateSignature (hash);
		byte[] sign2 = dsa.SignData (hash, 0, hash.Length);
		byte[] sign3 = dsa.SignData (new MemoryStream (hash));

		// we don't need the private key to verify
		DSAParameters param = dsa.ExportParameters (false);
		DSACryptoServiceProvider key = (DSACryptoServiceProvider) DSA.Create ();
		key.ImportParameters (param);
		// the signature is never the same so the only way to know if 
		// it worked is to verify it ourselve (i.e. can't compare)
		bool ok = key.VerifySignature (hash, sign1);
		Assert.IsTrue (ok, msg + "-CreateSignature-VerifySignature");

		ok = key.VerifyHash (hash, null, sign1);
		Assert.IsTrue (ok, msg + "-CreateSignature-VerifyHash");

		ok = key.VerifyData (hash, sign2);
		Assert.IsTrue (ok, msg + "-SignData(byte[])-VerifyData");

		ok = key.VerifyData (hash, sign3);
		Assert.IsTrue (ok, msg + "-SignData(Stream)-VerifyData");
	}
        private static void Sign(IList<string> args)
        {
            if (args.Count != 3)
            {
                Usage();
                Environment.Exit(-1);
            }

            // get parameter
            var artifact = args[1];
            var privKey = args[2];

            if (!File.Exists(artifact))
            {
                ShowErrorMessage(string.Format("\tArtifact {0} doesn't exist", artifact));
            }

            if (!File.Exists(privKey))
            {
                ShowErrorMessage(string.Format("\tPrivate key {0} doesn't exist", privKey));
            }

            string key;
            using (var reader = new StreamReader(privKey))
            {
                key = reader.ReadToEnd();
            }

            var prv = new DSACryptoServiceProvider();
            prv.FromXmlString(key);

            byte[] hash;
            using (Stream inputStream = File.OpenRead(artifact))
            {
                hash = prv.SignData(inputStream);
            }

            var base64Hash = Convert.ToBase64String(hash);
            Console.WriteLine(base64Hash);
        }
Exemple #19
0
        ///// <summary>
        /////		FromXml null
        ///// </summary>
        //private static void FromXmlNull()
        //{
        //    DSA alg = DSA.Create();
        //    alg.FromXmlString(null);
        //    return;
        //}

        ///// <summary>
        /////		FromXml no P
        ///// </summary>
        //private static void FromXmlNoP()
        //{
        //    XmlDocument doc = new XmlDocument();
        //    DSA alg = DSA.Create();
        //    doc.LoadXml(alg.ToXmlString(true));

        //    XmlElement remElem = doc.SelectSingleNode("/DSAKeyValue/P") as XmlElement;
        //    remElem.ParentNode.RemoveChild(remElem);

        //    alg.FromXmlString(doc.DocumentElement.OuterXml);
        //    return;
        //}

        ///// <summary>
        /////		FromXml no Q
        ///// </summary>
        //private static void FromXmlNoQ()
        //{
        //    XmlDocument doc = new XmlDocument();
        //    DSA alg = DSA.Create();
        //    doc.LoadXml(alg.ToXmlString(true));

        //    XmlElement remElem = doc.SelectSingleNode("/DSAKeyValue/Q") as XmlElement;
        //    remElem.ParentNode.RemoveChild(remElem);

        //    alg.FromXmlString(doc.DocumentElement.OuterXml);
        //    return;
        //}

        ///// <summary>
        /////		FromXml no G
        ///// </summary>
        //private static void FromXmlNoG()
        //{
        //    XmlDocument doc = new XmlDocument();
        //    DSA alg = DSA.Create();
        //    doc.LoadXml(alg.ToXmlString(true));

        //    XmlElement remElem = doc.SelectSingleNode("/DSAKeyValue/G") as XmlElement;
        //    remElem.ParentNode.RemoveChild(remElem);

        //    alg.FromXmlString(doc.DocumentElement.OuterXml);
        //    return;
        //}

        ///// <summary>
        /////		FromXml no Y
        ///// </summary>
        //private static void FromXmlNoY()
        //{
        //    XmlDocument doc = new XmlDocument();
        //    DSA alg = DSA.Create();
        //    doc.LoadXml(alg.ToXmlString(true));

        //    XmlElement remElem = doc.SelectSingleNode("/DSAKeyValue/Y") as XmlElement;
        //    remElem.ParentNode.RemoveChild(remElem);

        //    alg.FromXmlString(doc.DocumentElement.OuterXml);
        //    return;
        //}

        ///// <summary>
        /////		FromXml seed, no pgencounter
        ///// </summary>
        //private static void FromXmlSeedNoPgenCounter()
        //{
        //    XmlDocument doc = new XmlDocument();
        //    DSA alg = DSA.Create();
        //    doc.LoadXml(alg.ToXmlString(true));

        //    XmlElement remElem = doc.SelectSingleNode("/DSAKeyValue/PgenCounter") as XmlElement;
        //    remElem.ParentNode.RemoveChild(remElem);

        //    alg.FromXmlString(doc.DocumentElement.OuterXml);
        //    return;
        //}

        ///// <summary>
        /////		FromXml pgencounter, no seed
        ///// </summary>
        //private static void FromXmlNoSeedPgenCounter()
        //{
        //    XmlDocument doc = new XmlDocument();
        //    DSA alg = DSA.Create();
        //    doc.LoadXml(alg.ToXmlString(true));

        //    XmlElement remElem = doc.SelectSingleNode("/DSAKeyValue/Seed") as XmlElement;
        //    remElem.ParentNode.RemoveChild(remElem);

        //    alg.FromXmlString(doc.DocumentElement.OuterXml);
        //    return;
        //}
        #endregion

        #region DSA CSP API Tests
        /// <summary>
        ///		Create with CspParameters
        /// </summary>
        //private static bool CSPParameters()
        //{
        //    byte[] data = new byte[] { 0, 1, 2, 3, 4, 5 };

        //    CspParameters csp = new CspParameters(13);
        //    csp.KeyContainerName = "Custom Key Container";
        //    csp.KeyNumber = 2;

        //    DSACryptoServiceProvider dsaCsp = new DSACryptoServiceProvider(csp);
        //    byte[] signed = dsaCsp.SignData(data);
        //    bool passed = dsaCsp.VerifyData(data, signed);
        //    dsaCsp.Clear();

        //    return passed;
        //}

        ///// <summary>
        /////		Check KeyExchangeAlgorithm
        ///// </summary>
        //private static bool CSPCheckKeyExchangeAlg()
        //{
        //    return new DSACryptoServiceProvider().KeyExchangeAlgorithm == null;
        //}

        ///// <summary>
        /////		Check SignatureAlgorithm
        ///// </summary>
        //private static bool CSPCheckSignatureAlg()
        //{
        //    return new DSACryptoServiceProvider().SignatureAlgorithm == "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
        //}

        ///// <summary>
        /////		Check MachineStore
        ///// </summary>
        //private static bool CSPCheckMachineStore()
        //{
        //    bool init = DSACryptoServiceProvider.UseMachineKeyStore;

        //    DSACryptoServiceProvider.UseMachineKeyStore = true;
        //    bool ok = DSACryptoServiceProvider.UseMachineKeyStore;

        //    DSACryptoServiceProvider.UseMachineKeyStore = false;
        //    ok = ok && !DSACryptoServiceProvider.UseMachineKeyStore;

        //    DSACryptoServiceProvider.UseMachineKeyStore = init;
        //    return ok;
        //}

        /// <summary>
        ///		Sign stream
        /// </summary>
        private static bool CSPSignStream()
        {
            byte[] data = new byte[1025];
            for (int i = 2; i < data.Length; i++)
                data[i] = (byte)((data[i - 1] + data[i - 2]) % Byte.MaxValue);

            using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider())
            using (MemoryStream ms = new MemoryStream(data))
            {
                byte[] streamSig = dsa.SignData(ms);

                return dsa.VerifyData(data, streamSig);
            }
        }
Exemple #20
0
 /// <summary>
 ///		Clear, then try to use
 /// </summary>
 private static void CSPClearUse()
 {
     using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider())
     {
         dsa.SignData(new byte[] { 0, 1, 2, 3, 4, 5 });
         dsa.Clear();
         dsa.SignData(new byte[] { 0, 1, 2, 3, 4, 5 });
     }
 }
Exemple #21
0
        static void Main(string[] args)
        {
            try
            {
                // check if we have some parameters
                if (args.Count() < 1)
                {
                    Usage();
                    return;
                }

                // check what parameter we have
                switch (args[0].ToLower())
                {
                    case "/genkey_pair":
                        {
                            // show headline
                            ShowHeadLine();

                            // verify if output file exists
                            if (File.Exists(_dsaPrivKey) || File.Exists(_dsaPubKey))
                            {
                                Console.WriteLine("Error: Output files are currently exists");
                                Environment.ExitCode = -1;
                                return;
                            }

                            // start key generation
                            Console.WriteLine("Generating key pair with 1024 Bits...");
                            DSACryptoServiceProvider prv = new DSACryptoServiceProvider();

                            Console.WriteLine("Storing private key to " + _dsaPrivKey);
                            using (StreamWriter sw = new StreamWriter(_dsaPrivKey))
                            {
                                sw.Write(prv.ToXmlString(true));
                            }

                            Console.WriteLine("Storing public key to " + _dsaPubKey);
                            using (StreamWriter sw = new StreamWriter(_dsaPubKey))
                            {
                                sw.Write(prv.ToXmlString(false));
                            }

                            Console.WriteLine("");
                        }
                        break;
                    case "/sign_update":
                        {
                            if (args.Count() != 3)
                            {
                                Usage();
                                Environment.ExitCode = -1;
                                return;
                            }

                            // get parameter
                            String binary = args[1];
                            String privKey = args[2];

                            if (!File.Exists(binary))
                            {
                                Console.Error.WriteLine("Target binary " + binary + " does not exists");
                                Environment.ExitCode = -1;
                                return;
                            }

                            if (!File.Exists(privKey))
                            {
                                Console.Error.WriteLine("Private key file does not exists");
                                Environment.ExitCode = -1;
                                return;
                            }

                            // Reading private key
                            String key = null;
                            using (StreamReader reader = new StreamReader(privKey))
                            {
                                key = reader.ReadToEnd();
                            }

                            DSACryptoServiceProvider prv = new DSACryptoServiceProvider();
                            prv.FromXmlString(key);

                            // open stream
                            Byte[] hash = null;
                            using (Stream inputStream = File.OpenRead(binary))
                            {
                                hash = prv.SignData(inputStream);
                            }

                            String base64Hash = Convert.ToBase64String(hash);
                            Console.WriteLine(base64Hash);
                        }
                        break;
                    case "/verify_update":
                        {
                            if (args.Count() != 4)
                            {
                                Usage();
                                Environment.ExitCode = -1;
                                return;
                            }

                            // get parameter
                            String binary = args[1];
                            String pubKey = args[2];
                            String sign = args[3];

                            sign = sign.TrimStart('"');
                            sign = sign.TrimEnd('"');

                            AppLimit.NetSparkle.NetSparkleDSAVerificator dsaVerif = new AppLimit.NetSparkle.NetSparkleDSAVerificator(pubKey);
                            if (dsaVerif.VerifyDSASignature(sign, binary))
                                Console.WriteLine("Binary " + binary + " is valid");
                            else
                                Console.WriteLine("Binary " + binary + " is NOT valid");
                        }
                        break;
                    default:
                        Usage();
                        break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Something went wrong :-(");
                Console.WriteLine(e.StackTrace);
            }
        }
        /// <inheritdoc cref="Owasp.Esapi.Interfaces.IEncryptor.Sign(string)" />
        public string Sign(string data)
        {
            if (data == null) {
                throw new ArgumentNullException();
            }

            // Since this is the only asymmetric algorithm with signing capabilities, its hardcoded.
            // The more general APIs just aren't friendly.
            DSACryptoServiceProvider dsaCsp = new DSACryptoServiceProvider(asymmetricKeyPair);
            Encoding textConverter = Encoding.GetEncoding(encoding);
            byte[] dataBytes = textConverter.GetBytes(data);
            byte[] signatureBytes = dsaCsp.SignData(dataBytes);
            return Convert.ToBase64String(signatureBytes);
        }
 /// <summary> Create a digital signature for the provided data and return it in a
 /// string.
 /// </summary>
 /// <param name="data">The data to sign.
 /// </param>
 /// <returns> The signature.
 /// </returns>
 /// <seealso cref="Owasp.Esapi.Interfaces.IEncryptor.Sign(string)">
 /// </seealso>
 public string Sign(string data)
 {
     try
     {
         asymmetricKeyPair.Flags = CspProviderFlags.UseMachineKeyStore;
         DSACryptoServiceProvider dsaCsp = new DSACryptoServiceProvider(asymmetricKeyPair);
         Encoding textConverter = Encoding.GetEncoding(encoding);
         byte[] dataBytes = textConverter.GetBytes(data);
         byte[] signatureBytes = dsaCsp.SignData(dataBytes);
         bool valid = dsaCsp.VerifyData(dataBytes, signatureBytes);
         return Esapi.Encoder().EncodeForBase64(signatureBytes, true);
     }
     catch (Exception e)
     {
         throw new EncryptionException("Signature failure" + e.StackTrace, "Can't find signature algorithm " + signatureAlgorithm, e);
     }
 }
        private static byte[] DSASignHash(byte[] HashValue, DSAParameters privatekeyinfo, string HashAlg)
        {
            byte[] sig = null;

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

                    // 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 to the hash value and return it
                          //To format files                              // To format hash data                            
                    sig = dsa.SignData(HashValue, 0, HashValue.Length); //dsa.SignHash(HashValue, "SHA1"); //dsaFormatter.CreateSignature(HashValue);
                                        
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return sig;
        }