GenerateKey() приватный Метод

private GenerateKey ( ) : void
Результат void
Пример #1
0
 static void ByMSMQ()
 {
     Console.WriteLine("Opening MSMQ...");
     //messageQueue = !MessageQueue.Exists(QueueName) ? MessageQueue.Create(QueueName) : new MessageQueue(QueueName);4
     messageQueue = new MessageQueue(QueueName);
     Console.WriteLine("Server is ready");
     Console.WriteLine("Launch client app");
     RSA_public_key_receive();
     Console.WriteLine("Receiving open RSA-key...");
     Console.WriteLine("Making DES-key...");
     des_provider = new DESCryptoServiceProvider();
     des_provider.GenerateKey();
     des_provider.GenerateIV();
     Console.WriteLine("Crypt DES-key with open RSA-key...");
     DES_key = Encrypt_RSA(des_provider.Key);
     Console.WriteLine("Sending encrypted DES-key and initialization vector(IV)...");
     messageQueue.Send(DES_key);
     messageQueue.Send(des_provider.IV);
     Console.WriteLine("Getting data from Access...");
     GetData();
     Console.WriteLine("Crypt data...");
     var myMemoryStream = new MemoryStream();
     EncryptAndSerialize(myMemoryStream, data_to_recieve.ToArray());
     Console.WriteLine("Transfering data...");
     //Console.WriteLine("length = " + myMemoryStream.Length);
     messageQueue.Send(myMemoryStream.ToArray());
     Console.WriteLine("Successfull");
     Console.ReadKey();
 }
Пример #2
0
 /// <summary>
 /// 生成随机的Key和初始化向量
 /// </summary>
 /// <returns>随机的Key和初始化向量</returns>
 public virtual DESKey GenerateRandomKey()
 {
     var des = new DESCryptoServiceProvider();
     des.GenerateIV();
     des.GenerateKey();
     return new DESKey
     {
         IV = des.IV,
         Key = des.Key
     };
 }
Пример #3
0
    public static NCryptoParms EncryptCode(string decData, string spKey) {
      NCryptoParms parms = new NCryptoParms();
      ICryptoTransform encryptor;
      CryptoStream cStream;
      MemoryStream mStream = new MemoryStream();

      try {
        // Generate a new RSA public/private key pair
        // This key will be used to signature the DES IV and Key.
        RSACryptoServiceProvider jRsa = new RSACryptoServiceProvider();

        byte[] signature = jRsa.SignData(sign, new MD5CryptoServiceProvider());

        parms.jpbkey =
          Convert.ToBase64String(Encoding.ASCII.GetBytes(jRsa.ToXmlString(false)));
        parms.jprkey =
          Convert.ToBase64String(Encoding.ASCII.GetBytes(jRsa.ToXmlString(true)));
        parms.signature = Convert.ToBase64String(signature);
        jRsa.Clear();

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.FromXmlString(
          Encoding.ASCII.GetString(Convert.FromBase64String(spKey)));

        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.GenerateIV();
        des.GenerateKey();

        parms.key = Convert.ToBase64String(rsa.Encrypt(des.Key, false));
        parms.iv = Convert.ToBase64String(rsa.Encrypt(des.IV, false));

        encryptor = des.CreateEncryptor(des.Key, des.IV);
        cStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write);

        byte[] bytesIn = Encoding.ASCII.GetBytes(decData);

        cStream.Write(bytesIn, 0, bytesIn.Length);
        cStream.FlushFinalBlock();
        cStream.Close();

        byte[] bytesOut = mStream.ToArray();
        mStream.Close();

        parms.enc = Convert.ToBase64String(bytesOut);
      } catch {
        mStream.Close();
      }
      return parms;
    }
Пример #4
0
 /// <summary>
 /// 加密数据 
 /// </summary>
 /// <param name="Text"></param>
 /// <param name="key"></param>
 /// <param name="iv"></param>
 /// <returns></returns>
 public static string Encrypt(string Text, out string key, out string iv)
 {
     key = "";
     iv = "";
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     byte[] inputByteArray = Encoding.Default.GetBytes(Text);
     des.GenerateIV();
     des.GenerateKey();
     iv = new UnicodeEncoding().GetString(des.IV);
     key = new UnicodeEncoding().GetString(des.Key);
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     StringBuilder ret = new StringBuilder();
     foreach (byte b in ms.ToArray())
     {
         ret.AppendFormat("{0:X2}", b);
     }
     return ret.ToString();
 }
        static void Main(string[] args)
        {
            Console.Title = "文件加密";

            FileStream file = File.OpenRead("300 classic examples.txt");//以只读方式打开文件
            byte[] fileArray = new byte[file.Length];               //缓存文件
            file.Read(fileArray, 0, fileArray.Length);              //读取文件内容
            file.Close();

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();//DES加密算法服务对象
            des.GenerateKey();                                      //生成DES加密密钥
            des.GenerateIV();                                       //生成DES加密初始化向量
            Console.WriteLine("DES加密密钥为:");
            foreach (var item in des.Key) Console.Write(string.Format("{0:X2}", item));
            Console.WriteLine("\nDES加密初始化向量为:");
            foreach (var item in des.IV) Console.Write(string.Format("{0:X2}", item));
            FileStream fileKey = File.Create("Key");                //将Key存储到文件中
            fileKey.Write(des.Key, 0, des.Key.Length);
            fileKey.Close();
            FileStream fileIV = File.Create("IV");                  //将IV存储到文件中
            fileIV.Write(des.IV, 0, des.IV.Length);
            fileIV.Close();

            MemoryStream memoryStream = new MemoryStream();         //创建内存流对象
            //创建加密流对象
            CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(fileArray, 0, fileArray.Length);     //将文件内容加密后的文件写入内存流中
            cryptoStream.FlushFinalBlock();
            FileStream fileEncrypt = File.Create("300 classic examples.encrypt");//加密后的文件
            //将加密的文件内容写入到文件中
            foreach (byte value in memoryStream.ToArray()) fileEncrypt.WriteByte(value);
            Console.WriteLine("\n文件已加密!\n密文保存到文件300 classic examples.encrypt中");
            fileEncrypt.Close();
            cryptoStream.Close();
            memoryStream.Close();

            Console.ReadLine();
        }
        /// <summary>
        /// Método genera claves automaticamente.
        /// </summary>
        /// <returns>
        /// Mensajes de impresión.
        /// </returns>
        public static string GenerarClavesAutomaticamente()
        {
            // Declara mensajes de impresión.
            string vMsgImpresion = string.Empty;

            // Crea instancia de DESCryptoServiceProvider.
            // Crear claves simétricas automáticamente.
            DESCryptoServiceProvider vServicioCriptograficoDES = new DESCryptoServiceProvider();

            // Genera claves.
            vServicioCriptograficoDES.GenerateIV();
            vServicioCriptograficoDES.GenerateKey();

            // Asigna las claves generadas a variables.
            byte[] vClaveIV = vServicioCriptograficoDES.IV;
            byte[] vClaveKey = vServicioCriptograficoDES.Key;

            // Asigna mensajes.
            vMsgImpresion += "GENERACION AUTOMATICA (DES): La longitud de la clave (KeySize) es de " + vServicioCriptograficoDES.KeySize + " bytes. \n ";
            vMsgImpresion += "GENERACION AUTOMATICA (DES): La longitud de la clave es de " + vClaveKey.Length + " bytes \n ";

            // Retorna mensaje.
            return vMsgImpresion;
        }
Пример #7
0
 /// <summary>
 /// 加密
 /// </summary>
 /// <param name="input"></param>
 /// <param name="key"></param>
 /// <param name="iv"></param>
 /// <returns></returns>
 public static string Encrypt(string input,out string key,out string iv)
 {
     key = "";
     iv = "";
     DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
     byte[] bytes = Encoding.Default.GetBytes(input);
     provider.GenerateIV();
     provider.GenerateKey();
     iv = new UnicodeEncoding().GetString(provider.IV);
     key = new UnicodeEncoding().GetString(provider.Key);
     MemoryStream stream = new MemoryStream();
     CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
     stream2.Write(bytes, 0, bytes.Length);
     stream2.FlushFinalBlock();
     StringBuilder sb = new StringBuilder();
     var sarray = stream.ToArray();
     foreach (var item in sarray)
     {
         sb.AppendFormat("{0:X2}", item);
     }
     stream.Close();
     stream2.Close();
     return sb.ToString();
 }
Пример #8
0
        static void BySocket()
        {
            Console.WriteLine("Creating a socket...");
            const int port = 13000;
            var localAddr = IPAddress.Parse("127.0.0.1");
            var listener = new TcpListener(localAddr, port);
            listener.Start();
            Console.WriteLine("Server is ready");
            Console.WriteLine("Launch client app");
            var clientSocket = listener.AcceptSocket();
            if (clientSocket.Connected)
            {
                RSA_public_key = new byte[276];
                Console.WriteLine("Getting open RSA-key...");
                clientSocket.Receive(RSA_public_key);
                Console.WriteLine("Generating DES-key...");
                des_provider = new DESCryptoServiceProvider();
                des_provider.GenerateKey();
                des_provider.GenerateIV();
                Console.WriteLine("Encrypting DES with open RSA...");
                DES_key = Encrypt_RSA(des_provider.Key);
                Console.WriteLine("Sending encrypted DES...");
                clientSocket.Send(DES_key);
                clientSocket.Send(des_provider.IV);
                Console.WriteLine("Getting data from db...");
                GetData();
                Console.WriteLine("Crypting data...");
                var myMemoryStream = new MemoryStream();
                EncryptAndSerialize(myMemoryStream, data_to_recieve.ToArray());
                Console.WriteLine("Transfering data...");
                //send byte[2], где byte[0]*256 + byte[1] = myMemoryStream.ToArray().Length
                clientSocket.Send(new[] { (byte)(myMemoryStream.ToArray().Length / 256), (byte)(myMemoryStream.ToArray().Length % 256) });
                clientSocket.Send(myMemoryStream.ToArray());

                Console.WriteLine("Successfully");
            }
            clientSocket.Close();
            listener.Stop();
            Console.ReadKey();
        }
Пример #9
0
 public void GenerateKey(out string key, out string iv)
 {
     key = "";
     iv = "";
     using (DESCryptoServiceProvider des_o = new DESCryptoServiceProvider())
     {
         des_o.GenerateIV();
         des_o.GenerateKey();
         iv = Convert.ToBase64String(des_o.IV);
         key = Convert.ToBase64String(des_o.Key);
     }
 }
Пример #10
0
        /// <summary>
        /// 授权编码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        internal static String Encode(String text)
        {
            String xml = text;
#if ISMANAGE
            //签名。XCode生成的Lic文件不包含签名,防止私钥泄露
            xml += "$"+ License.Sign(Encoding.UTF8.GetBytes(xml), PrivateKey);
#else
            xml += "$";
#endif
            //DES加密
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            //IV的明文
            String key = "mama shuo wo zhang da le";
            //加密IV
            des.GenerateIV();
            String iv = Convert.ToBase64String(Encrypt(des.IV, key));
            //生成一个Key
            des.GenerateKey();
            key = Convert.ToBase64String(des.Key);
            key = key + "|" + iv;
            //DES加密
            xml = Encrypt(xml, key);
            xml += "@" + key;
            //RC4加密
            Byte[] bts = Encrypt(Encoding.UTF8.GetBytes(xml), InternalKey);
            return Convert.ToBase64String(bts);
        }
Пример #11
0
 /// <summary>
 /// 产生密钥。
 /// </summary>
 /// <returns></returns>
 private static string GenKey()
 {
     SymmetricAlgorithm csp = new DESCryptoServiceProvider();
     csp.GenerateKey();
     return Convert.ToBase64String(csp.Key);
 }