您的位置:首页 > 编程语言 > C#

远程桌面,RDP文件密码加密、解密算法(C#)

2016-02-19 11:32 846 查看
背景:由于项目需要,使用RDP文件来远程登录,需要实现点击rdp文件就可以自动连接远程桌面,并且实现自动登录功能!自动登录!自动登录!

自动登录:密码需要经过加密,本文的核心!!!废话少说,看代码!

1、首先添加引用是必须的!

      using System;

      using System.Security.Cryptography;

2、核心算法

        private void test()

        {

            string plainText = "qweR+-*yuioP0";

            byte[] secret = Encoding.Unicode.GetBytes(plainText);

            byte[] encryptedSecret = Protect(secret);

            Console.WriteLine("The encrypted byte array is:");

            string res = string.Empty;

            foreach(byte b in encryptedSecret)

            {

                res += b.ToString("X2");                          //炒鸡坑爹的,转换16进制的一定要用2位,不然就像我一样被坑了半个多月

            }

            

            Console.WriteLine("加密之后的密码:" + res);

            PrintValues(encryptedSecret);

            // Decrypt the data and store in a byte array.

            byte[] originalData = Unprotect(encryptedSecret);

            Console.WriteLine("{0}The original data is:", Environment.NewLine);

            string str = Encoding.Default.GetString(originalData);

            Console.WriteLine("解密之后的密码: " + str);

            PrintValues(originalData);

        }

        //加密方法

        public static byte[] Protect(byte[] data)

        {

            try

            {

                // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted

                //  only by the same current user.

                return ProtectedData.Protect(data, s_aditionalEntropy, DataProtectionScope.LocalMachine);

            }

            catch (CryptographicException e)

            {

                Console.WriteLine("Data was not encrypted. An error occurred.");

                Console.WriteLine(e.ToString());

                return null;

            }

        }

        //解密方法

        public static byte[] Unprotect(byte[] data)

        {

            try

            {

                //Decrypt the data using DataProtectionScope.CurrentUser.

                return ProtectedData.Unprotect(data, s_aditionalEntropy, DataProtectionScope.LocalMachine);

            }

            catch (CryptographicException e)

            {

                Console.WriteLine("Data was not decrypted. An error occurred.");

                Console.WriteLine(e.ToString());

                return null;

            }

        }

        public static void PrintValues(Byte[] myArr)

        {

            foreach (Byte i in myArr)

            {

                Console.Write("\t{0}", i);

            }

            Console.WriteLine();

        }

3、总结!

     生成的字节数组直接转换成16进制输出,添加到rdp文件的密码里面就会解析不出来。

     坑爹的转换成16进制时需要占位2位,不然就出错,弄了N久才搞定,发文共勉!转载请注明出处,谢谢!

4、附RDP文件的一些注释(转)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息