ExportParameters() public method

public ExportParameters ( bool includePrivateParameters ) : DSAParameters
includePrivateParameters bool
return DSAParameters
Exemplo n.º 1
0
        public static void DoTest()
        {
            Console.WriteLine("使用  DSACryptoServiceProvider 类创建哈希值的数字签名,然后验证签名的例子!");

            // 创建一个   DSA 算法的加密服务提供程序 (CSP) 实现的包装对象.
            DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

            // 需要被签名的数据.
            byte[] HashValue = { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };

            Console.WriteLine("初始 Hash 数据.");
            ByteArrayOutput.Print(HashValue);

            // 签名处理.
            byte[] SignedHashValue = DSASignHash(HashValue, DSA.ExportParameters(true), "SHA1");

            Console.WriteLine("使用私钥签名的数据.");
            ByteArrayOutput.Print(SignedHashValue);

            // 验证签名.
            if (DSAVerifyHash(HashValue, SignedHashValue, DSA.ExportParameters(false), "SHA1"))
            {
                Console.WriteLine("使用公钥验证 签名是有效的!");
            }
            else
            {
                Console.WriteLine("使用公钥验证 签名无效.");
            }
        }
        static void Main(string[] args)
        {
            try
            {
                DSAParameters privatekeyinfo;
                DSAParameters publickeyinfo;

                //Create a new instance of DSACryptoServiceProvider to generate a new key pair.
                using(DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
                {
                    privatekeyinfo = DSA.ExportParameters(true);
                    publickeyinfo = DSA.ExportParameters(false);
                    byte[] HashValue;

                    using(FileStream fs = new FileStream(@"C:\Listener.txt", FileMode.Open, FileAccess.Read))
                    {
                        BinaryReader reader = new BinaryReader(fs);

                        HashValue = reader.ReadBytes((int)fs.Length);

                        //HashValue = new byte[fs.Length];
                        //fs.Read(HashValue, 0, (int)fs.Length);

                        //The hash value to sign
                        //HashValue = new byte[20]{
                        //                            59, 4, 248, 102, 77, 97, 142, 201,
                        //                            210, 12, 224, 93, 25, 41, 100, 197,
                        //                            213, 134, 130, 135
                        //                        };
                    }

                    string OId = CryptoConfig.MapNameToOID("SHA1");

                    //The value to hold the signed value.
                    byte[] SignedHashValue = DSASignHash(HashValue, privatekeyinfo, OId);

                    //Verify the hash and display the results.
                    bool verified = DSAVerifyHash(HashValue, SignedHashValue, publickeyinfo, "SHA1");

                    if(verified)
                    {
                        Console.WriteLine("The hash value was verified.");
                    }
                    else
                    {
                        Console.WriteLine("The hash value was not verified.");
                    }
                }

                Console.ReadKey();
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 3
0
        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 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();
        }
Exemplo n.º 6
0
        public void init(int key_size)
        {
            //			KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
            //			keyGen.initialize(key_size, new SecureRandom());
            //			KeyPair pair = keyGen.generateKeyPair();
            //			PublicKey pubKey=pair.getPublic();
            //			PrivateKey prvKey=pair.getPrivate();

            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(key_size);
            DSAParameters DSAKeyInfo = dsa.ExportParameters(true);

            //			x=((DSAPrivateKey)prvKey).getX().toByteArray();
            //			y=((DSAPublicKey)pubKey).getY().toByteArray();
            //
            //			DSAParams _params=((DSAKey)prvKey).getParams();
            //			p=_params.getP().toByteArray();
            //			q=_params.getQ().toByteArray();
            //			g=_params.getG().toByteArray();

            x = DSAKeyInfo.X;
            y = DSAKeyInfo.Y;
            p = DSAKeyInfo.P;
            q = DSAKeyInfo.Q;
            g = DSAKeyInfo.G;
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
        public void init(int key_size)
        {
            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(key_size);
            DSAParameters DSAKeyInfo = dsa.ExportParameters(true);

            m_x = DSAKeyInfo.X;
            m_y = DSAKeyInfo.Y;
            m_p = DSAKeyInfo.P;
            m_q = DSAKeyInfo.Q;
            m_g = DSAKeyInfo.G;
        }
Exemplo n.º 9
0
        public void EncodePublicKey(IPublicKey publicKey, ByteBuf buffer)
        {
            var dsa = new DSACryptoServiceProvider();
            var dsap = dsa.ExportParameters(false);


            var rsa = new RSACryptoServiceProvider();
            var rsap = rsa.ExportParameters(false);


        }
Exemplo n.º 10
0
        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));
        }
Exemplo n.º 11
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();
        }
        public bool GenerateKeyPair(string pubPath, string privPath)
        {
            try
            {
                using (DSACryptoServiceProvider dsaProvider = new DSACryptoServiceProvider())
                {

                    DSAParameters publicKey = dsaProvider.ExportParameters(false);//pub
                    var binformt = new BinaryFormatter();
                    using (var fs = new FileStream(pubPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                    {
                        //binformt.Serialize(fs, publicKey.Counter);

                        binformt.Serialize(fs, publicKey.Q);
                        binformt.Serialize(fs, publicKey.Seed);
                        binformt.Serialize(fs, publicKey.G);
                        binformt.Serialize(fs, publicKey.P);
                        binformt.Serialize(fs, publicKey.Counter);
                        binformt.Serialize(fs, publicKey.Y);
                        //binformt.Serialize(fs, publicKey.X);
                        binformt.Serialize(fs, publicKey.J);
                        fs.Close();
                    }
                    //File.WriteAllBytes(pubPath, memoryStream.GetBuffer());

                    DSAParameters privateKey = dsaProvider.ExportParameters(true);//generate private key
                    var binformt1 = new BinaryFormatter();
                    //var memoryStream1 = new MemoryStream();
                    using (var fs = new FileStream(privPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                    {
                        binformt.Serialize(fs, privateKey.Q);
                        binformt.Serialize(fs, privateKey.Seed);
                        binformt.Serialize(fs, privateKey.G);
                        binformt.Serialize(fs, privateKey.P);
                        binformt.Serialize(fs, privateKey.Counter);
                        binformt.Serialize(fs, privateKey.Y);
                        binformt.Serialize(fs, privateKey.X);
                        binformt.Serialize(fs, privateKey.J);
                        fs.Close();
                    }
                    //File.WriteAllBytes(privPath, memoryStream1.GetBuffer());
                    //File.WriteAllBytes(privPath, keyData);
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
Exemplo n.º 13
0
        public void TestMethodSerialization()
        {
            //on simule l'ajout d'auteur
            User aut1 = new User("Toto", "mypass1");
            User aut2 = new User("JC", "mypass2");
            User aut3 = new User("Max", "mypass3");
            User aut4 = new User("Titi", "clearstream");
            User aut5 = new User("Toadd", "serie");

            DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider();
            DSAParameters key = mycrypto.ExportParameters(false);
            aut1.Publickey = key;
            aut2.Publickey = key;
            aut3.Publickey = key;
            aut4.Publickey = key;
            aut5.Publickey = key;

            Message mess1 = new Message(aut1.Login, "Coucou ca va?");
            Message mess2 = new Message(aut2.Login, "oue et toi?");
            Message mess3 = new Message(aut3.Login, "tranquille!");
            Message mess4 = new Message(aut1.Login, "ca va ca va");
            Message mess5 = new Message(aut5.Login, "Test fifi");
            Message mess6 = new Message(aut5.Login, "MessagePrive: cool ma poule?");

            aut1.AddPrivateMessage(mess6);

            //on simule
            Chat toTest = new Chat();
            Chat toOut =  new Chat();
            toTest.AddUser(aut1);
            toTest.AddUser(aut2);
            toTest.AddUser(aut3);
            toTest.AddUser(aut4);
            toTest.AddMessage(mess1);
            toTest.AddMessage(mess2);
            toTest.AddMessage(mess3);
            toTest.AddMessage(mess4);

            toTest.Serialiser();
            toOut.Deserialiser();
            toOut.AddUser(aut5);
            toOut.AddMessage(mess5);
            toOut.Serialiser();
            //l'analyse du test se fera manuellement dans le fichier de sortie
        }
Exemplo n.º 14
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;
        }
Exemplo n.º 15
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");
        }
Exemplo n.º 16
0
        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");
        }
Exemplo n.º 17
0
        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");
        }
Exemplo n.º 18
0
		public static DsaPublicKeyParameters GetDsaPublicKey(
			DSACryptoServiceProvider dsaCsp)
		{
			return GetDsaPublicKey(dsaCsp.ExportParameters(false));
		}
Exemplo n.º 19
0
		public static AsymmetricCipherKeyPair GetDsaKeyPair(
			DSACryptoServiceProvider dsaCsp)
		{
			return GetDsaKeyPair(dsaCsp.ExportParameters(true));
		}
Exemplo n.º 20
0
        public static void testSign()
        {
            //Create a new instance of DSACryptoServiceProvider to generate
            //a new key pair.
            DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

            //The hash value to sign.
            byte[] HashValue = { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };

            //The value to hold the signed value.
            byte[] SignedHashValue = mySignHash(HashValue, DSA.ExportParameters(true), "SHA1");

            //Verify the hash and display the results.
            if (myVerifyHash(HashValue, SignedHashValue, DSA.ExportParameters(false), "SHA1"))
            {
                Console.WriteLine("The hash value was verified.");
            }
            else
            {
                Console.WriteLine("The hash value was not verified.");
            }
        }
Exemplo n.º 21
0
        public static Boolean Test(Session session)
        {
            Boolean bRes = true;
            //String xml1, xml2, xml3;
            //String sign1, sign2, sign3;
            byte[] hashval = new byte[20];
            for (int i = 0; i < hashval.Length; i++) hashval[i] = (Byte)i;

            DSACryptoServiceProvider dsa1 = new DSACryptoServiceProvider(session);
            DSACryptoServiceProvider dsa2 = new DSACryptoServiceProvider(session);
            //DSACryptoServiceProvider dsa3 = new DSACryptoServiceProvider(session);

            DSAParameters dsaParams = dsa1.ExportParameters(true);

            byte[] sig1 = dsa1.SignHash(hashval, MechanismType.SHA_1);

            //sign1 = (Convert.ToBase64String(sig1));

            //xml1 = dsa1.ToXmlString(true);


            dsa2.ImportParameters(dsaParams);
            //dsa2.FromXmlString(xml1);

            //xml2 = (dsa2.ToXmlString(true));
            //xml3 = (dsa3.ToXmlString(true));

            byte[] sig2 = dsa2.SignHash(hashval, MechanismType.SHA_1);
            //sign2 = (Convert.ToBase64String(sig2));

            //dsa3.HashAlgorithm = MechanismType.SHA_1;
            //byte[] sig3 = dsa3.SignHash(hashval);
            //sign3 = (Convert.ToBase64String(sig3));

            //if ((xml1 != xml2) || (xml2 != xml3))
            //{
            //    Log.Comment("WRONG : ToXmlString results are different");
            //    Log.Comment("XML1:\n" + xml1);
            //    Log.Comment("XML2:\n" + xml2);
            //    Log.Comment("XML3:\n" + xml3);
            //    bRes = false;
            //}

            //Log.Comment(xml1);

            /*        if ( (sign1!=sign2) || (sign2!=sign3) ) {
                        Log.Comment("WRONG : signatures are different");
                        Log.Comment("First: " + sign1);
                        Log.Comment("Second: " + sign2);
                        Log.Comment("Third: " + sign3);
        	
                        bRes = false;
                    } */

            //Log.Comment("\n" + sign1);

            if (!dsa1.VerifyHash(hashval, MechanismType.SHA_1, sig2))
            {
                Log.Comment("WRONG : Signature check (1) failed");
                bRes = false;
            }
            if (!dsa2.VerifyHash(hashval, MechanismType.SHA_1, sig1))
            {
                Log.Comment("WRONG : Signature check (1) failed");
                bRes = false;
            }
            //if (!dsa3.VerifyHash(hashval, sig1))
            //{
            //    Log.Comment("WRONG : Signature check (1) failed");
            //    bRes = false;
            //}

            return bRes;
        }
 private static AsymmetricCipherKeyPair GenerateDsaKeys()
 {
     DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
     var dsaParams = DSA.ExportParameters(true);
     AsymmetricCipherKeyPair keys = DotNetUtilities.GetDsaKeyPair(dsaParams);
     return keys;
 }
Exemplo n.º 23
0
	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");
	}
Exemplo n.º 24
0
        // -------------------------------------------------------------------------------
        /// <summary>
        /// SignedEncrypts the plaintext.
        /// </summary>
        /// <param name="plaintext">The plaintext to be encrypted.</param>
        /// <param name="compressStreamWriter">A StreamWriter for the compressing the stream</param>
        /// <returns>The encrypted plaintext (-> ciphertext).</returns>
        private byte[] SignedEncrypt(byte[] plaintext, CompressStreamWriterDelegate compressStreamWriter)
        {
            byte[] ciphertext = null;

            MemoryStream memoryStream = new MemoryStream();
            byte[] IV = new byte[16];

            //Creates the default implementation, which is RijndaelManaged.
            SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            //RNGCryptoServiceProvider is an implementation of a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            // The array is now filled with cryptographically strong random bytes, and none are zero.
            rng.GetNonZeroBytes(IV);

            // creates a symmetric encryptor object with the specified Key and initialization vector (IV).
            ICryptoTransform encryptor = rijn.CreateEncryptor(this.key, IV);

            // write the unencrypted initialization vector
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, IV);

            // write the digital signature and the DSA parameters
            SHA1 sha1Provider = new SHA1CryptoServiceProvider();
            DSACryptoServiceProvider dsaProvider = new DSACryptoServiceProvider();
            byte[] hashbytes = sha1Provider.ComputeHash(plaintext);
            byte[] signature = dsaProvider.SignHash(hashbytes, CryptoConfig.MapNameToOID(SHA1));
            formatter.Serialize(memoryStream, signature);

            // very important !!!!
            // only the public key is serialized -> false as argument to ExportParameters.
            formatter.Serialize(memoryStream, dsaProvider.ExportParameters(false));

            if (compressStreamWriter != null)
            {
                // write plaintext into compressed and encrypted stream
                MemoryStream compressedStream = new MemoryStream();
                using (Stream sw = compressStreamWriter(compressedStream))
                {
                    sw.Write(plaintext, 0, plaintext.Length);
                    sw.Flush();
                    sw.Close();
                }

                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(compressedStream.ToArray(), 0, compressedStream.ToArray().Length);
                    cryptoStream.Flush();
                    cryptoStream.Close();
                }
            }
            else
            {
                // write plaintext into encrypted stream
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plaintext, 0, plaintext.Length);
                    cryptoStream.Flush();
                    cryptoStream.Close();
                }
            }

            ciphertext = memoryStream.ToArray();

            return ciphertext;
        }
Exemplo n.º 25
0
 public override KeyPair GenerateKeyPair()
 {
     DSACryptoServiceProvider dsa = new DSACryptoServiceProvider (keySize);
     DSAParameters dsaPars = dsa.ExportParameters (true);
     return new KeyPair (new DSAPrivateKey (dsaPars), new DSAPublicKey (dsaPars));
 }
Exemplo n.º 26
0
        public static void Main()
        {
            try
            {

            DSAParameters privateKeyInfo;
            DSAParameters publicKeyInfo;

            //Создаем пару ключей(открытый и закрытый)
            using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
            {
                privateKeyInfo = DSA.ExportParameters(true);
                publicKeyInfo = DSA.ExportParameters(false);
            }
            // Хеш таблица
            byte[] HashValue = new byte[20];
            Console.WriteLine("Введите хеш-таблица размером 20 символов: ");
            string TextIn = Console.ReadLine();
            HashValue = Convert.FromBase64String(Convert.ToBase64String(Encoding.UTF8.GetBytes(TextIn)));
            //Хеш таблица состоит из 20 бит, через консоль вводимые
            string text = Encoding.UTF8.GetString(HashValue);
            Console.WriteLine(text);
            // Подписываем хеш-таблицу с помощью закрытого ключа
            byte[] SignedHashValue = DSASignHash(HashValue, privateKeyInfo, "SHA1");
            text = Encoding.UTF8.GetString(SignedHashValue);

            Console.WriteLine(text);
            // Сверяем подписанную неподписанную Хеш-таблицу с помощью открытого ключа
            bool verified = DSAVerifyHash(HashValue, SignedHashValue, publicKeyInfo, "SHA1");

            if (verified)
            {
                Console.WriteLine("Значение хеш-таблицы совпало");
            }
            else
            {
                Console.WriteLine("Значение хеш-таблицы не совпало");
            }
            }
            catch (ArgumentNullException e)
            {
            Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }