Exemplo n.º 1
0
	private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
	 {
	     //Create the file streams to handle the input and output files.
	     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
	     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
	     fout.SetLength(0);

	     //Create variables to help with read and write.
	     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
	     long rdlen = 0;              //This is the total number of bytes written.
	     long totlen = fin.Length;    //This is the total length of the input file.
	     int len;                     //This is the number of bytes to be written at a time.

	     SymmetricAlgorithm des = new DESCryptoServiceProvider();
         des.Padding = PaddingMode.PKCS7;
	     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

	     Console.WriteLine("Encrypting...");

	     //Read from the input file, then encrypt and write to the output file.
	     while(rdlen < totlen)
	     {
	         len = fin.Read(bin, 0, 100);
	         encStream.Write(bin, 0, len);
	         rdlen = rdlen + len;
             Console.WriteLine("{0} bytes processed", rdlen);
         }
	     encStream.Close();
    }
Exemplo n.º 2
0
    public static string Encrypt(string originalString, string sKey)
    {
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            // 把字符串放到byte数组中
            byte[] inputByteArray = Encoding.Default.GetBytes(originalString);

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);  //原文使用ASCIIEncoding.ASCII方法的

                                                            //GetBytes方法
            MemoryStream ms = new 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);
            }
            ret.ToString();
            return ret.ToString();
    }
Exemplo n.º 3
0
	public static string Crypt(this string text)
	{
		try
		{
			//SymmetricAlgorithm algorithm = DES.Create();
			DES des = new DESCryptoServiceProvider();
			des.Mode = CipherMode.ECB;
			des.Padding = PaddingMode.PKCS7;
			des.Key = key;
			des.IV = iv;
			//ICryptoTransform transform = algorithm.CreateEncryptor(key, iv);
			ICryptoTransform transform = des.CreateEncryptor(key,iv);
			byte[] inputbuffer = Encoding.Unicode.GetBytes(text);
			byte[] outputBuffer;
			try
			{
				outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length);
			}
			catch(Exception e)
			{
				inputbuffer = Encoding.UTF8.GetBytes(text);
				outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length);
			}
			string asdfs = Convert.ToBase64String(outputBuffer);
			return asdfs;
		}
		catch (Exception e)
		{
			return "";
		}

	}
    public string Encrypt(string item, string password)
    {
        if (item == null) {
            throw new ArgumentNullException ("item");
        }

        if (string.IsNullOrEmpty (password)) {
            throw new ArgumentNullException ("password");
        }

        var des = new DESCryptoServiceProvider ();

        des.GenerateIV ();

        var rfc2898DeriveBytes = new Rfc2898DeriveBytes (password, des.IV, ITERATIONS);

        byte[] key = rfc2898DeriveBytes.GetBytes (8);

        using (var memoryStream = new MemoryStream()) {
            using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, des.IV), CryptoStreamMode.Write)) {
                memoryStream.Write (des.IV, 0, des.IV.Length);

                byte[] bytes = Encoding.UTF8.GetBytes (item);

                cryptoStream.Write (bytes, 0, bytes.Length);
                cryptoStream.FlushFinalBlock ();

                return Convert.ToBase64String (memoryStream.ToArray ());
            }
        }
    }
Exemplo n.º 5
0
Arquivo: test.cs Projeto: mono/gert
	static int Main ()
	{
		string filename = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"encrypt.tmp");
		string data = "this is sensitive data";

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

		// -----------  WRITING ENCRYPTED SERIALIZED DATA ------------------
		Stream stream = new FileStream (filename, FileMode.Create, FileAccess.Write);
		stream = new CryptoStream (stream, des.CreateEncryptor (), CryptoStreamMode.Write);
		BinaryFormatter bformatter = new BinaryFormatter ();
		bformatter.Serialize (stream, data);
		stream.Close ();

		stream = null;
		bformatter = null;
		data = string.Empty;

		// -----------  READING ENCRYPTED SERIALIZED DATA ------------------
		stream = new FileStream (filename, FileMode.Open, FileAccess.Read);
		stream = new CryptoStream (stream, des.CreateDecryptor (), CryptoStreamMode.Read);
		bformatter = new BinaryFormatter ();
		data = (string) bformatter.Deserialize (stream);
		stream.Close ();

		//----------- CHECK RESULTS ----------------
		if (data != "this is sensitive data")
			return 1;

		return 0;
	}
Exemplo n.º 6
0
 // 加密字符串
 public string EncryptString(string sInputString, string sKey)
 {
     byte[] data = Encoding.UTF8.GetBytes(sInputString);
     var DES = new DESCryptoServiceProvider {Key = Encoding.ASCII.GetBytes(sKey), IV = Encoding.ASCII.GetBytes(sKey)};
     ICryptoTransform desencrypt = DES.CreateEncryptor();
     byte[] result = desencrypt.TransformFinalBlock(data,0,data.Length);
     return BitConverter.ToString(result);
 }
Exemplo n.º 7
0
 public string Encrypt(string SourceData)
 {
     byte[] SourceDataBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(SourceData);
     MemoryStream TempStream = new MemoryStream();
     DESCryptoServiceProvider Encryptor = new DESCryptoServiceProvider();
     CryptoStream EncryptionStream = new CryptoStream(TempStream, Encryptor.CreateEncryptor(Key, Iv), CryptoStreamMode.Write);
     EncryptionStream.Write(SourceDataBytes, 0, SourceDataBytes.Length);
     EncryptionStream.FlushFinalBlock();
     byte[] EncryptedDataBytes = TempStream.GetBuffer();
     //MsgBox(Convert.ToBase64String(EncryptedDataBytes, 0, TempStream.Length))
     return  Convert.ToBase64String(EncryptedDataBytes,0, Convert.ToInt16(TempStream.Length));
 }
Exemplo n.º 8
0
 public static string DesEncrypt(string encryptString, string encrptKey)
 {
     if (string.IsNullOrEmpty(encrptKey)) encrptKey = Key;
     byte[] keyBytes = Encoding.UTF8.GetBytes(encrptKey);
     byte[] keyIV = keyBytes;
     byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
     DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
     MemoryStream mStream = new MemoryStream();
     CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
     cStream.Write(inputByteArray, 0, inputByteArray.Length);
     cStream.FlushFinalBlock();
     return Convert.ToBase64String(mStream.ToArray());
 }
    static Boolean Test()
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7}; //, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 2};
        Byte[]  IV = {1, 1, 1, 1, 1, 1, 1, 1};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        DESCryptoServiceProvider     des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
//        des.FeedbackSize = 0;
		des.Padding = PaddingMode.None;

        Console.WriteLine("DES default key size = " + des.KeySize);
        ICryptoTransform sse = des.CreateEncryptor(Key, IV);
        Console.WriteLine("SSE mode = " + des.Mode);
        MemoryStream ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] CipherText = ms.ToArray();
        cs.Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

//        DESCryptoServiceProvider     des = new DESCryptoServiceProvider();
//        des.Mode = CipherMode.ECB;
//        des.FeedbackSize = 0;
        ICryptoTransform ssd = des.CreateDecryptor(Key, IV);
        Console.WriteLine("SSD mode = " + des.Mode);
        cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read);

        byte[] NewPlainText = new byte[8];
        cs.Read(NewPlainText,0,8);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
Exemplo n.º 10
0
 public static string DESEncrypt(string input)
 {
     byte[] bytes = Encoding.ASCII.GetBytes((string)ConfigurationSettings.AppSettings["CipherKeyProd"]);
     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
     MemoryStream memoryStream = new MemoryStream();
     CryptoStream cryptoStream = new CryptoStream(memoryStream,
         cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
     StreamWriter writer = new StreamWriter(cryptoStream);
     writer.Write(input);
     writer.Flush();
     cryptoStream.FlushFinalBlock();
     writer.Flush();
     return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
 }
Exemplo n.º 11
0
    public static byte[] GetDesSignatureInBytes(byte[] data, byte[] sharedSecret)
    {
        HashAlgorithm hash = new SHA1Managed();
        byte[] hashedData = hash.ComputeHash(data);

        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.Key = sharedSecret;
        des.Mode = CipherMode.ECB;

        ICryptoTransform transform = des.CreateEncryptor();
        byte[] signature = new byte[8];
        transform.TransformBlock(hashedData, 0, signature.Length, signature, 0);

        return signature;
    }
Exemplo n.º 12
0
 /// <summary> 
 ///  MD5���� 
 /// </summary> 
 public static string MD5Encrypt(string Text, string sKey)
 {
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     byte[] inputByteArray = Encoding.Default.GetBytes(Text);
     des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
     des.IV =  ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
     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();
 }
Exemplo n.º 13
0
    public string Encrypt(string input)
    {
        string output = "";

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(cryptBytes, cryptBytes), CryptoStreamMode.Write);
        StreamWriter writer = new StreamWriter(cryptoStream);

        writer.Write(input);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();

        output = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        return output;
    }
Exemplo n.º 14
0
 /*
 ============================================================================
 DES handling functions
 ============================================================================
 */
 public static string EncryptDES(string text, byte[] key)
 {
     if(text != null && text != "")
     {
         DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
         MemoryStream memoryStream = new MemoryStream();
         CryptoStream cryptoStream = new CryptoStream(memoryStream,
                 cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);
         StreamWriter writer = new StreamWriter(cryptoStream);
         writer.Write(text);
         writer.Flush();
         cryptoStream.FlushFinalBlock();
         writer.Flush();
         text = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
     }
     return text;
 }
Exemplo n.º 15
0
 /// DES加密
 public string MD5Encrypt(string pToEncrypt, string sKey)
 {
     var des = new DESCryptoServiceProvider();
     byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
     des.Key = Encoding.ASCII.GetBytes(sKey);
     des.IV = Encoding.ASCII.GetBytes(sKey);
     var ms = new MemoryStream();
     var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     var ret = new StringBuilder();
     foreach (byte b in ms.ToArray())
     {
         ret.AppendFormat("{0:X2}", b);
     }
     ret.ToString();
     return ret.ToString();
 }
Exemplo n.º 16
0
 private string Encrypt(string pToEncrypt, string sKey)
 {
     DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
     byte[] bytes = Encoding.Default.GetBytes(pToEncrypt);
     provider.Key = Encoding.ASCII.GetBytes(sKey);
     provider.IV = Encoding.ASCII.GetBytes(sKey);
     MemoryStream stream = new MemoryStream();
     CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
     stream2.Write(bytes, 0, bytes.Length);
     stream2.FlushFinalBlock();
     StringBuilder builder = new StringBuilder();
     foreach (byte num in stream.ToArray())
     {
         builder.AppendFormat("{0:X2}", num);
     }
     builder.ToString();
     return builder.ToString();
 }
Exemplo n.º 17
0
        /// <summary>
        /// 对数据进行加密
        /// </summary>
        /// <param name="encryptstring">需要加密的数据</param>
        /// <returns></returns>
        public static string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }
Exemplo n.º 18
0
 public static string DESEncrypt(string str, string key)
 {
     try
         {
             byte[] rgbKey = System.Text.Encoding.UTF8.GetBytes(key);
             byte[] rgbIV = rgbKey;
             byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(str);
             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
             System.IO.MemoryStream mStream = new System.IO.MemoryStream();
             CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
             cStream.Write(inputByteArray, 0, inputByteArray.Length);
             cStream.FlushFinalBlock();
             return Convert.ToBase64String(mStream.ToArray());
         }
         catch
         {
             return "";
         }
 }
Exemplo n.º 19
0
 public static string DesEncrypt(string toEncryptString,string keyStr)
 {
     using (var des = new DESCryptoServiceProvider())
     {
         byte[] toEncryptBytes = Encoding.GetBytes(toEncryptString);
         des.Key = Encoding.GetBytes(keyStr);
         des.IV = Encoding.GetBytes(keyStr);
         var ms = new MemoryStream();
         using (var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
         {
             cs.Write(toEncryptBytes, 0, toEncryptBytes.Length);
             cs.FlushFinalBlock();
             cs.Close();
         }
         string encryptedString = Convert.ToBase64String(ms.ToArray());
         ms.Close();
         return encryptedString;
     }
 }
Exemplo n.º 20
0
    public string Encrypt(string Newword)
    {
        if (String.IsNullOrEmpty(Newword))
        {
            throw new ArgumentNullException("The string which needs to be encrypted can not be null.");
        }

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);

        StreamWriter writer = new StreamWriter(cryptoStream);
        writer.Write(Newword);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();

        return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
    }
 public string Encrypt(string stringToEncrypt, string SEncryptionKey)
 {
     try
     {
         key = System.Text.Encoding.UTF8.GetBytes(SEncryptionKey);
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
         MemoryStream ms = new MemoryStream();
         CryptoStream cs = new CryptoStream(ms,
           des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         return HttpUtility.UrlEncode(Convert.ToBase64String(ms.ToArray()));
     }
     catch (Exception e)
     {
         return e.Message;
     }
 }
Exemplo n.º 22
0
 /// <summary>
 /// DES加密字符串
 /// </summary>
 /// <param name="encryptString">待加密的字符串</param>
 /// <param name="encryptKey">加密密钥,要求为8位</param>
 /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
 public static string EncryptDES(string encryptString, string encryptKey)
 {
     try
     {
         byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
         byte[] rgbIV = Keys;
         byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
         DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
         MemoryStream mStream = new MemoryStream();
         CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
         cStream.Write(inputByteArray, 0, inputByteArray.Length);
         cStream.FlushFinalBlock();
         return Convert.ToBase64String(mStream.ToArray());
     }
     catch
     {
         return encryptString;
     }
 }
Exemplo n.º 23
0
		//
		// TODO: 在此处添加构造函数逻辑


        #region MD5加密                   
        /// <summary>   
        /// MD5加密   
        /// </summary>   
        /// <param name="strSource">需要加密的字符串</param>   
        /// <returns>MD5加密后的字符串</returns>   
        public string Md5Encrypt(string strSource)   
        {   
            //把字符串放到byte数组中   
            byte[] bytIn = System.Text.Encoding.Default.GetBytes(strSource);   
            //建立加密对象的密钥和偏移量           
            byte[] iv = { 103, 16, 93, 156, 78, 4, 218, 32 };//定义偏移量   
            byte[] key = { 55, 103, 246, 79, 36, 99, 167, 3 };//定义密钥   
            //实例DES加密类   
            DESCryptoServiceProvider mobjCryptoService = new DESCryptoServiceProvider();   
            mobjCryptoService.Key = iv;   
            mobjCryptoService.IV = key;   
            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();   
            //实例MemoryStream流加密密文件   
            System.IO.MemoryStream ms = new System.IO.MemoryStream();   
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);   
            cs.Write(bytIn, 0, bytIn.Length);   
            cs.FlushFinalBlock();   
            return System.Convert.ToBase64String(ms.ToArray());   
        }  
Exemplo n.º 24
0
    /// <summary>
    /// Standard DES encryption
    /// </summary>
    /// <param name="val">Accepts value to be encrypted using DES</param>
    /// <returns>Returns value encrypted in DES</returns>
    public static string Encrypt(string val)
    {
        string encrypted = "";
        if (val != "") {
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_64, IV_64), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cs);

            sw.Write(val);
            sw.Flush();
            cs.FlushFinalBlock();
            ms.Flush();

            //convert back to string - added explicit conversion to int32
            encrypted = Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
        }
        return encrypted;
    }
Exemplo n.º 25
0
    public static string EncryptPassword(string passwd)
    {
        // Use standard VNC Server Key
        byte[] rawKey = new byte[8];
        rawKey[0] = 23;
        rawKey[1] = 82;
        rawKey[2] = 107;
        rawKey[3] = 6;
        rawKey[4] = 35;
        rawKey[5] = 78;
        rawKey[6] = 88;
        rawKey[7] = 7;
        // revert it
        rawKey = FixDESBug(rawKey);
        byte[] Passwd_Bytes = new byte[8];
        if (passwd.Length >= 8)
        {
            Encoding.ASCII.GetBytes(passwd, 0, 8, Passwd_Bytes, 0);
        }
        else
        {
            Encoding.ASCII.GetBytes(passwd, 0, passwd.Length, Passwd_Bytes, 0);
        }

        // VNC uses DES, not 3DES as written in some documentation
        DES des = new DESCryptoServiceProvider();
        des.Padding = PaddingMode.None;
        des.Mode = CipherMode.ECB;

        ICryptoTransform enc = des.CreateEncryptor(rawKey, null);

        byte[] passwd_enc = new byte[8];
        enc.TransformBlock(Passwd_Bytes, 0, Passwd_Bytes.Length, passwd_enc, 0);
        string ret = "";

        for (int i = 0; i < 8; i++)
        {
            ret += passwd_enc[i].ToString("x2");
        }
        return ret;
    }
Exemplo n.º 26
0
    public string Encrypt(string plainText, string password)
    {
        if (plainText == null)
        {
            throw new ArgumentNullException("plainText");
        }

        if (string.IsNullOrEmpty(password))
        {
            throw new ArgumentNullException("password");
        }

        // create instance of the DES crypto provider
        var des = new DESCryptoServiceProvider();

        // generate a random IV will be used a salt value for generating key
        des.GenerateIV();

        // use derive bytes to generate a key from the password and IV
        var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, des.IV, Iterations);

        // generate a key from the password provided
        byte[] key = rfc2898DeriveBytes.GetBytes(8);

        // encrypt the plainText
        using (var memoryStream = new MemoryStream())
        using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, des.IV), CryptoStreamMode.Write))
        {
            // write the salt first not encrypted
            memoryStream.Write(des.IV, 0, des.IV.Length);

            // convert the plain text string into a byte array
            byte[] bytes = Encoding.UTF8.GetBytes(plainText);

            // write the bytes into the crypto stream so that they are encrypted bytes
            cryptoStream.Write(bytes, 0, bytes.Length);
            cryptoStream.FlushFinalBlock();

            return Convert.ToBase64String(memoryStream.ToArray());
        }
    }
Exemplo n.º 27
0
    private string EnCryption(string content, string sKey, string sIV)
    {
        using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
        {
            byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(content);
            desProvider.Key = System.Text.Encoding.ASCII.GetBytes(sKey);
            desProvider.IV = System.Text.Encoding.ASCII.GetBytes(sIV);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            using (CryptoStream cs = new CryptoStream(ms,desProvider.CreateEncryptor(), CryptoStreamMode.Write))
            {
                //cs.Clear();
                cs.Write(inputByteArray,0,inputByteArray.Length);
                cs.FlushFinalBlock();
                cs.Close();
            }

            string str = Convert.ToBase64String(ms.ToArray());
            ms.Close();
            return str;
        }
    }
Exemplo n.º 28
0
	public void Save() 
	{
		// using(Stream stream = File.Open("save01.sav", FileMode.Create)) // 1. create backing storage stream. In your case a file stream
			
		using(Stream stream = File.Open("save01.sav", FileMode.Create)) {
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			binaryFormatter.Binder = new VersionDeserializationBinder(); 
			
			byte[] byKey = Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
			using(DESCryptoServiceProvider des = new DESCryptoServiceProvider()) {
				using(Stream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(byKey, dv), CryptoStreamMode.Write)) // 2. create a CryptoStream in write mode
				{
					Log.debug("Save", "Saving...");
					using(cryptoStream)
						binaryFormatter.Serialize(cryptoStream, this); // 3. write to the cryptoStream
					cryptoStream.Close();
				}
			}
			stream.Close();
		}
		Log.debug("Save", "Saved");
	}
Exemplo n.º 29
0
    //cmThe function used to encrypt the text
    private static string Encrypt(string strText, string SaltKey)
    {
        byte[] byKey = { };
        byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };

        try
        {
            byKey = System.Text.Encoding.UTF8.GetBytes(SaltKey.Substring(0, 8));

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
Exemplo n.º 30
0
    // AIM: THIS FUNCTION IS USE FOR ENCRYPT THE USER PASSWORD FOR SECURITY CONCERN
    // USE PASS THE PASSWORD AS STRING THEN IT WRITTEN THE THE DATA INTO ENCRYPTED FORM.
    public string Encrypt(string stringToEncrypt)
    {
        string sEncryptionKey = "54276498933473847874";
        byte[] key = { };
        byte[] IV = { 0xAB, 0x90, 0xEF, 0xCD, 0x34, 0x78, 0x12, 0x56 };
        byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)

        try
        {
            key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }
        catch (Exception ex)
        {
            return (string.Empty);
        }
    }
Exemplo n.º 31
0
        internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            ICryptoTransform iCryptoTransform;

            switch (algorithmID)
            {
            case EncryptionAlgorithm.Des:
                DES dES = new DESCryptoServiceProvider();
                dES.Mode = CipherMode.CBC;
                if (bytesKey == null)
                {
                    encKey = dES.Key;
                }
                else
                {
                    dES.Key = bytesKey;
                    encKey  = dES.Key;
                }
                if (initVec == null)
                {
                    initVec = dES.IV;
                }
                else
                {
                    dES.IV = initVec;
                }
                iCryptoTransform = dES.CreateEncryptor();
                break;

            case EncryptionAlgorithm.TripleDes:
                TripleDES tripleDES = new TripleDESCryptoServiceProvider();
                tripleDES.Mode = CipherMode.CBC;
                if (bytesKey == null)
                {
                    encKey = tripleDES.Key;
                }
                else
                {
                    tripleDES.Key = bytesKey;
                    encKey        = tripleDES.Key;
                }
                if (initVec == null)
                {
                    initVec = tripleDES.IV;
                }
                else
                {
                    tripleDES.IV = initVec;
                }
                iCryptoTransform = tripleDES.CreateEncryptor();
                break;

            case EncryptionAlgorithm.Rc2:
                RC2 rC2 = new RC2CryptoServiceProvider();
                rC2.Mode = CipherMode.CBC;
                if (bytesKey == null)
                {
                    encKey = rC2.Key;
                }
                else
                {
                    rC2.Key = bytesKey;
                    encKey  = rC2.Key;
                }
                if (initVec == null)
                {
                    initVec = rC2.IV;
                }
                else
                {
                    rC2.IV = initVec;
                }
                iCryptoTransform = rC2.CreateEncryptor();
                break;

            case EncryptionAlgorithm.Rijndael:
                Rijndael rijndael = new RijndaelManaged();
                rijndael.Mode = CipherMode.CBC;
                if (bytesKey == null)
                {
                    encKey = rijndael.Key;
                }
                else
                {
                    rijndael.Key = bytesKey;
                    encKey       = rijndael.Key;
                }
                if (initVec == null)
                {
                    initVec = rijndael.IV;
                }
                else
                {
                    rijndael.IV = initVec;
                }
                iCryptoTransform = rijndael.CreateEncryptor();
                break;

            default:
                throw new CryptographicException(String.Concat("Algorithm ID \'", algorithmID, "\' not supported."));
            }
            return(iCryptoTransform);
        }
Exemplo n.º 32
0
        public string Encrypt(EncoderType type, string encrypt)
        {
            string ret = "";

            byte[] inputByteArray = Encoding.UTF8.GetBytes(encrypt);
            byte[] rgbKey         = Convert.FromBase64String(Key);
            byte[] rgbIV          = Convert.FromBase64String(IV);
            switch (type)
            {
            case EncoderType.AES:
                using (AesCryptoServiceProvider csp = new AesCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.DES:
                using (DESCryptoServiceProvider csp = new DESCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.RC2:
                using (RC2CryptoServiceProvider csp = new RC2CryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.TripleDES:
                using (TripleDESCryptoServiceProvider csp = new TripleDESCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.RSA:
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    csp.FromXmlString(Key);
                    ret = Convert.ToBase64String(csp.Encrypt(inputByteArray, false));
                }
                break;

            case EncoderType.MD5:
                using (MD5CryptoServiceProvider csp = new MD5CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA1:
                using (SHA1CryptoServiceProvider csp = new SHA1CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA256:
                using (SHA256CryptoServiceProvider csp = new SHA256CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA384:
                using (SHA384CryptoServiceProvider csp = new SHA384CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA512:
                using (SHA512CryptoServiceProvider csp = new SHA512CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;
            }
            return(ret);
        }
Exemplo n.º 33
0
        /// <summary>
        /// This method registers our RepGen Services (we support 2 - pre/post 9.6)
        /// </summary>
        /// <param name="services"></param>
        private void RegisterRepGen(IServiceCollection services)
        {
            services.Configure <ReportOptions>(Configuration.GetSection("ReportService"));
            services.Configure <ReportConnectionOptions>((rco) =>
            {
                using (DESCryptoServiceProvider DES = new DESCryptoServiceProvider()
                {
                    Key = new byte[] { 0xEF, 0x9C, 0xD1, 0x2F, 0x91, 0x76, 0x85, 0x1C },
                    Mode = CipherMode.ECB
                })
                {
                    using (ICryptoTransform DESEncrypt = DES.CreateEncryptor())
                    {
                        byte[] Buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Configuration.GetConnectionString("EngineDb"));
                        rco.EncryptedConnectionString = Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
                    }
                }
            });

            // 9.5 Resolution
            services.AddScoped <RepGen95.PERepGenSoap>(sp =>
            {
                var options       = sp.GetRequiredService <IOptions <ReportOptions> >();
                var reportOptions = options.Value;
                // Build up the Service
                var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
                binding.MaxBufferPoolSize      = 524288;
                binding.MaxBufferSize          = Int32.MaxValue;
                binding.MaxReceivedMessageSize = Int32.MaxValue;
                binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
                binding.ReaderQuotas.MaxArrayLength         = Int32.MaxValue;
                binding.ReaderQuotas.MaxBytesPerRead        = 4096;
                binding.ReaderQuotas.MaxNameTableCharCount  = 16384;
                binding.SendTimeout     = TimeSpan.FromMinutes(15);
                EndpointAddress address = new EndpointAddress(reportOptions.URL);
                return(new RepGen95.PERepGenSoapClient(binding, address));
            });

            // 9.6 Resolution
            services.AddScoped <RepGen96.PERepGenSoap>(sp =>
            {
                var options       = sp.GetRequiredService <IOptions <ReportOptions> >();
                var reportOptions = options.Value;
                // Build up the Service
                var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
                binding.MaxBufferPoolSize      = 524288;
                binding.MaxBufferSize          = Int32.MaxValue;
                binding.MaxReceivedMessageSize = Int32.MaxValue;
                binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
                binding.ReaderQuotas.MaxArrayLength         = Int32.MaxValue;
                binding.ReaderQuotas.MaxBytesPerRead        = 4096;
                binding.ReaderQuotas.MaxNameTableCharCount  = 16384;
                binding.SendTimeout     = TimeSpan.FromMinutes(15);
                EndpointAddress address = new EndpointAddress(reportOptions.URL);
                return(new RepGen96.PERepGenSoapClient(binding, address));
            });
            // 9.6 Authentication
            services.AddScoped <RepGen96.AuthenticationInformation>(sp =>
            {
                return(new RepGen96.AuthenticationInformation
                {
                    Authorization = "305df5f62dacf9c2eea8ac82d1524317363a592d8d62a556c0e3ed2e9b41a360"
                });
            });
        }
Exemplo n.º 34
0
        protected string EncryptDES(string encryptString, string encryptKey)
        {
            string result;

            try
            {
                byte[] bytes  = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] keys   = this.Keys;
                byte[] bytes2 = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
                MemoryStream             memoryStream             = new MemoryStream();
                CryptoStream             cryptoStream             = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(bytes, keys), CryptoStreamMode.Write);
                cryptoStream.Write(bytes2, 0, bytes2.Length);
                cryptoStream.FlushFinalBlock();
                result = Convert.ToBase64String(memoryStream.ToArray());
            }
            catch
            {
                result = encryptString;
            }
            return(result);
        }
Exemplo n.º 35
0
Arquivo: VncHost.cs Projeto: tub5/NVNC
        /// <summary>
        /// If the password is not empty, perform VNC Authentication with it.
        /// </summary>
        /// <param name="password">The current VNC Password</param>
        /// <returns>Returns a boolean value representing successful authentication or not.</returns>
        public bool WriteAuthentication(string password)
        {
            // Indicate to the client which type of authentication will be used.
            //The type of Authentication to be used, 1 (None) or 2 (VNC Authentication).
            if (String.IsNullOrEmpty(password))
            {
                // Protocol Version 3.7 onward supports multiple security types, while 3.3 only 1
                if (verMinor == 3)
                {
                    WriteUint32(1);
                }
                else
                {
                    byte[] types = { 1 };
                    writer.Write((byte)types.Length);

                    for (int i = 0; i < types.Length; i++)
                    {
                        writer.Write(types[i]);
                    }
                }
                if (verMinor >= 7)
                {
                    reader.ReadByte();
                }
                if (verMinor == 8)
                {
                    WriteSecurityResult(0);
                }
                return(true);
            }
            if (verMinor == 3)
            {
                WriteUint32(2);
            }
            else
            {
                byte[] types = { 2 };
                writer.Write((byte)types.Length);

                for (int i = 0; i < types.Length; i++)
                {
                    writer.Write(types[i]);
                }
            }
            if (verMinor >= 7)
            {
                reader.ReadByte();
            }

            //A random 16 byte challenge
            byte[] bChallenge = new byte[16];
            Random rand       = new Random(DateTime.Now.Millisecond);

            rand.NextBytes(bChallenge);

            // send the bytes to the client and wait for the response
            writer.Write(bChallenge);
            writer.Flush();

            byte[] receivedBytes = reader.ReadBytes(16);
            byte[] key           = PasswordToKey(password);

            DES des = new DESCryptoServiceProvider();

            des.Padding = PaddingMode.None;
            des.Mode    = CipherMode.ECB;
            ICryptoTransform enc = des.CreateEncryptor(key, null);

            byte[] ourBytes = new byte[16];
            enc.TransformBlock(bChallenge, 0, bChallenge.Length, ourBytes, 0);

            /*
             *  Console.WriteLine("Us: " + System.Text.Encoding.ASCII.GetString(ourBytes));
             *  Console.WriteLine("Client sent us: " + System.Text.Encoding.ASCII.GetString(receivedBytes));
             */
            bool authOK = true;

            for (int i = 0; i < ourBytes.Length; i++)
            {
                if (receivedBytes[i] != ourBytes[i])
                {
                    authOK = false;
                }
            }

            if (authOK)
            {
                WriteSecurityResult(0);
                return(true);
            }
            WriteSecurityResult(1);
            if (verMinor != 8)
            {
                return(false);
            }
            string ErrorMsg = "Wrong password, sorry";

            WriteUint32((uint)ErrorMsg.Length);
            writer.Write(GetBytes(ErrorMsg));
            return(false);
        }
        // Uses the DES crypto provider to encrypt a string.
        // Used to encrypt the details before they are stored in the license file
        public static String Encrypt(String originalString, byte[] bytes)
        {
            if (String.IsNullOrEmpty(originalString))
            {
                throw new ArgumentNullException("The string which needs to be encrypted can not be null.");
            }

            using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(cryptoStream))
                        {
                            writer.Write(originalString);
                            writer.Flush();
                            cryptoStream.FlushFinalBlock();
                            writer.Flush();

                            return(Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
                        }
                    }
                }
            }
        }
Exemplo n.º 37
0
        /// <summary>
        /// DES 加密
        /// </summary>
        /// <param name="strInput">待加密的数据</param>
        /// <param name="KEY_64">KEY_64(8个字符64位)</param>
        /// <param name="IV_64">IV_64(8个字符64位)</param>
        /// <returns>加密后的数据</returns>
        public static string DesEncrypt(string strInput, string KEY_64, string IV_64)
        {
            DESCryptoServiceProvider cryptoProvider = null;
            MemoryStream             ms             = null;
            CryptoStream             cst            = null;
            StreamWriter             sw             = null;
            string strDesEncrypt = "";

            if (string.IsNullOrEmpty(strInput))
            {
                return("");
            }

            if (string.IsNullOrEmpty(KEY_64) || string.IsNullOrEmpty(IV_64))
            {
                return(strInput);
            }

            if (KEY_64.Length != 8 || IV_64.Length != 8)
            {
                return(strInput);
            }

            try
            {
                byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
                byte[] byIV  = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

                cryptoProvider = new DESCryptoServiceProvider();
                int i = cryptoProvider.KeySize;
                ms  = new MemoryStream();
                cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

                sw = new StreamWriter(cst);
                sw.Write(strInput);
                sw.Flush();
                cst.FlushFinalBlock();
                sw.Flush();

                strDesEncrypt = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

                return(strDesEncrypt);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }

                if (cst != null)
                {
                    cst.Dispose();
                }

                if (ms != null)
                {
                    ms.Close();
                    ms.Dispose();
                }

                if (cryptoProvider != null)
                {
                    cryptoProvider = null;
                }
            }
        }
        private bool _Save()
        {
            bool        ret      = true;
            clsResponse response = new clsResponse();

            // ▼ 設定データをバイト配列に変換する
            DataSet ds = new DataSet();

            ds.Tables.Add(myData_.Copy());

            MemoryStream ms = new MemoryStream();

            ds.WriteXml(ms, XmlWriteMode.IgnoreSchema);

            byte[] bytesIn = ms.ToArray();
            // ▲ 設定データをバイト配列に変換する

            // ▼ 暗号化する
            string key = clsCrypt.xGetPublicKey();

            //DESCryptoServiceProviderオブジェクトの作成
            DESCryptoServiceProvider
                des = new DESCryptoServiceProvider();

            //共有キーと初期化ベクタを決定
            //パスワードをバイト配列にする
            byte[] bytesKey = Encoding.UTF8.GetBytes(key);
            //共有キーと初期化ベクタを設定
            des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
            des.IV  = ResizeBytesArray(bytesKey, des.IV.Length);

            //暗号化されたデータを書き出すためのMemoryStream
            MemoryStream msOut = new MemoryStream();
            //DES暗号化オブジェクトの作成
            ICryptoTransform desdecrypt = des.CreateEncryptor();
            //書き込むためのCryptoStreamの作成
            CryptoStream cryptStreem = new CryptoStream(
                msOut, desdecrypt,
                CryptoStreamMode.Write);

            //書き込む
            cryptStreem.Write(bytesIn, 0, bytesIn.Length);
            cryptStreem.FlushFinalBlock();
            //暗号化されたデータを取得
            byte[] bytesOut = msOut.ToArray();

            //閉じる
            cryptStreem.Close();
            msOut.Close();
            // ▲ 暗号化する

            // ▼ ファイルに書き出す
            FileStream file = null;

            try
            {
                file = new FileStream(
                    myFileName_, FileMode.Create, FileAccess.Write);
                file.Write(bytesOut, 0, bytesOut.Length);
                file.Flush();
            }
            catch (Exception ex)
            {
                ret = false;
                string msg = ex.Message + ex.StackTrace;
                clsTextLogger.xWriteTextLog(
                    MethodBase.GetCurrentMethod().DeclaringType.FullName + "."
                    + MethodBase.GetCurrentMethod().Name, msg);
                return(ret);
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                    file.Dispose();
                    file = null;
                }
            }
            // ▲ ファイルに書き出す

            // ▼ アクセス権変更
            clsACL acl = null;

            try
            {
                acl      = new clsACL();
                response = acl.xChengeFileSecurity(myFileName_);
            }
            catch (Exception ex)
            {
                ret = false;
                response.xSetError(ex.Message + Environment.NewLine + ex.StackTrace);
            }
            if (response.xHasError)
            {
                ret = false;
                clsTextLogger.xWriteTextLog(
                    MethodBase.GetCurrentMethod().DeclaringType.FullName + "."
                    + MethodBase.GetCurrentMethod().Name, response.xMessage);
            }
            // ▲ アクセス権変更

            return(ret);
        }
Exemplo n.º 39
0
 /// <summary>
 /// DES 加密
 /// </summary>
 /// <param name="Values">要加密的字符串</param>
 /// <returns>加密后的字符串</returns>
 public string DESEncrypt(string Values)
 {
     try
     {
         DESCryptoServiceProvider DesHash = new DESCryptoServiceProvider();
         DesHash.Mode = CipherMode.CBC;
         byte[] byt;
         if (null == this._Key)
         {
             DesHash.GenerateKey();
             _Key = Encoding.ASCII.GetString(DesHash.Key);
         }
         else
         {
             if (_Key.Length > 8)
             {
                 _Key = _Key.Substring(0, 8);
             }
             else
             {
                 for (int i = 8; i < _Key.Length; i--)
                 {
                     _Key += "0";
                 }
             }
         }
         if (null == this._IV)
         {
             DesHash.GenerateIV();
             _IV = Encoding.ASCII.GetString(DesHash.IV);
         }
         else
         {
             if (_IV.Length > 8)
             {
                 _IV = _IV.Substring(0, 8);
             }
             else
             {
                 for (int i = 8; i < _IV.Length; i--)
                 {
                     _IV += "0";
                 }
             }
         }
         //return _Key + ":" + Encoding.ASCII.GetBytes(_Key).Length.ToString() + "<br>"+ _IV + ":" + Encoding.ASCII.GetBytes(this._IV).Length.ToString();
         byt = Encoding.UTF8.GetBytes(Values);
         ICryptoTransform ct = DesHash.CreateEncryptor(Encoding.ASCII.GetBytes(this._Key), Encoding.ASCII.GetBytes(this._IV));
         DesHash.Clear();
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         CryptoStream           cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
         cs.Write(byt, 0, byt.Length);
         cs.FlushFinalBlock();
         cs.Close();
         return(Convert.ToBase64String(ms.ToArray()));
     }
     catch (System.Exception e)
     {
         throw new System.Exception("加密数据出错,详细原因:" + e.Message);
     }
 }
Exemplo n.º 40
0
 public byte[] Encrypt(byte[] data)
 {
     return(cryptoHelper.CryptoTransform(DESProvider.CreateEncryptor(), data));
 }
Exemplo n.º 41
0
        public static byte[] DESEncrypt(byte[] data, byte[] cryptKey = null, byte[] cryptIV = null)
        {
            DESCryptoServiceProvider dESCryptoServiceProvider = EncryptHelper.CreateDESCrypto();
            MemoryStream             memoryStream             = new MemoryStream();
            CryptoStream             cryptoStream             = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(cryptKey, cryptIV), CryptoStreamMode.Write);

            cryptoStream.Write(data, 0, data.Length);
            cryptoStream.FlushFinalBlock();
            return(memoryStream.ToArray());
        }
Exemplo n.º 42
0
        /// <summary>
        ///  Encrypt passing content.
        /// </summary>
        /// <param name="stringToEncrypt">Content to encrypt.</param>
        /// <returns>Encrypted contain.</returns>
        public static string Encrypt(string stringToEncrypt)
        {
            byte[] key;
            byte[] IV;

            byte[] inputByteArray;
            try
            {
                key = Convert2ByteArray(DESKey);

                IV = Convert2ByteArray(DESIV);

                inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);

                cs.FlushFinalBlock();

                return(Convert.ToBase64String(ms.ToArray()));
            }

            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        public static string Encrypt(string strData)
        {
            string strValue = " ";

            if (!string.IsNullOrEmpty(strKey))
            {
                if (strKey.Length < 16)
                {
                    char c = "XXXXXXXXXXXXXXXX"[16];
                    strKey = strKey + strKey.Substring(0, 16 - strKey.Length);
                }

                if (strKey.Length > 16)
                {
                    strKey = strKey.Substring(0, 16);
                }

                // create encryption keys
                byte[] byteKey    = Encoding.UTF8.GetBytes(strKey.Substring(0, 8));
                byte[] byteVector = Encoding.UTF8.GetBytes(strKey.Substring(strKey.Length - 8, 8));

                // convert data to byte array
                byte[] byteData = Encoding.UTF8.GetBytes(strData);

                // encrypt
                DESCryptoServiceProvider objDES          = new DESCryptoServiceProvider();
                MemoryStream             objMemoryStream = new MemoryStream();
                CryptoStream             objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateEncryptor(byteKey, byteVector), CryptoStreamMode.Write);
                objCryptoStream.Write(byteData, 0, byteData.Length);
                objCryptoStream.FlushFinalBlock();

                // convert to string and Base64 encode
                strValue = Convert.ToBase64String(objMemoryStream.ToArray());
            }
            else
            {
                strValue = strData;
            }

            return(strValue);
        }
Exemplo n.º 44
0
        public static string EncryptString(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return("");
            }

            //文字列をバイト型配列にする
            var bytesIn = Encoding.UTF8.GetBytes(str);

            //DESCryptoServiceProviderオブジェクトの作成
            using (var des = new DESCryptoServiceProvider())
            {
                //共有キーと初期化ベクタを決定
                //パスワードをバイト配列にする
                var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
                //共有キーと初期化ベクタを設定
                des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
                des.IV  = ResizeBytesArray(bytesKey, des.IV.Length);

                MemoryStream     msOut      = null;
                ICryptoTransform desdecrypt = null;

                try
                {
                    //暗号化されたデータを書き出すためのMemoryStream
                    msOut = new MemoryStream();

                    //DES暗号化オブジェクトの作成
                    desdecrypt = des.CreateEncryptor();

                    //書き込むためのCryptoStreamの作成
                    using (CryptoStream cryptStream = new CryptoStream(msOut, desdecrypt, CryptoStreamMode.Write))
                    {
                        //Disposeが重複して呼ばれないようにする
                        MemoryStream msTmp = msOut;
                        msOut      = null;
                        desdecrypt = null;

                        //書き込む
                        cryptStream.Write(bytesIn, 0, bytesIn.Length);
                        cryptStream.FlushFinalBlock();
                        //暗号化されたデータを取得
                        var bytesOut = msTmp.ToArray();

                        //Base64で文字列に変更して結果を返す
                        return(Convert.ToBase64String(bytesOut));
                    }
                }
                finally
                {
                    if (msOut != null)
                    {
                        msOut.Dispose();
                    }
                    if (desdecrypt != null)
                    {
                        desdecrypt.Dispose();
                    }
                }
            }
        }
Exemplo n.º 45
0
 public static string Encriptar(string valor)
 {
     try
     {
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         byte[] inputByteArray        = System.Text.Encoding.UTF8.GetBytes(valor);
         System.IO.MemoryStream ms    = new System.IO.MemoryStream();
         System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(key, IV), System.Security.Cryptography.CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         return(Convert.ToBase64String(ms.ToArray()));
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
Exemplo n.º 46
0
        /// <summary>
        /// Des加密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">des密钥,长度必须8位</param>
        /// <param name="iv">密钥向量</param>
        /// <returns>加密后的字符串</returns>
        public static string EncryptDes(string source, string key, byte[] iv)
        {
            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                byte[] rgbKeys = GetDesKey(key),
                rgbIvs         = iv,
                inputByteArray = Encoding.UTF8.GetBytes(source);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desProvider.CreateEncryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                        cryptoStream.FlushFinalBlock();
                        // 1.第一种
                        return(Convert.ToBase64String(memoryStream.ToArray()));

                        // 2.第二种
                        //StringBuilder result = new StringBuilder();
                        //foreach (byte b in memoryStream.ToArray())
                        //{
                        //    result.AppendFormat("{0:X2}", b);
                        //}
                        //return result.ToString();
                    }
                }
            }
        }
Exemplo n.º 47
0
        /// <summary>
        /// Define un objeto para la operaciones básicas de transformaciones
        /// criptográficas.
        /// </summary>
        /// <param name="Key">Clave de encripción.</param>
        /// <param name="IV">Vector de inicialización.</param>
        /// <returns>Devuelve el objeto que implementa la interfaz ICryptoTransform.
        /// </returns>
        internal ICryptoTransform GetServiceProvider(byte[] Key, byte[] IV)
        {
            // creamos la variable que contendrá al objeto ICryptoTransform.
            ICryptoTransform transform = null;

            // dependiendo del algoritmo seleccionado, se devuelve el objeto adecuado.
            switch (this.algorithm)
            {
            // Algoritmo DES.
            case CryptoProvider.DES:
                // dependiendo de la acción a realizar.
                // creamos el objeto adecuado.
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                switch (cAction)
                {
                case CryptoAction.Encrypt:        // si estamos cifrando,
                    // creamos el objeto cifrador.
                    transform = des.CreateEncryptor(Key, IV);
                    break;

                case CryptoAction.Desencrypt:        // sí estamos descifrando,
                    // creamos el objeto descifrador.
                    transform = des.CreateDecryptor(Key, IV);
                    break;
                }
                // devolvemos el objeto transform correspondiente.
                return(transform);

            // algoritmo TripleDES.
            case CryptoProvider.TripleDES:
                TripleDESCryptoServiceProvider des3 = new TripleDESCryptoServiceProvider();
                switch (cAction)
                {
                case CryptoAction.Encrypt:
                    transform = des3.CreateEncryptor(Key, IV);
                    break;

                case CryptoAction.Desencrypt:
                    transform = des3.CreateDecryptor(Key, IV);
                    break;
                }
                return(transform);

            // algoritmo RC2.
            case CryptoProvider.RC2:
                RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
                switch (cAction)
                {
                case CryptoAction.Encrypt:
                    transform = rc2.CreateEncryptor(Key, IV);
                    break;

                case CryptoAction.Desencrypt:
                    transform = rc2.CreateDecryptor(Key, IV);
                    break;
                }
                return(transform);

            // algoritmo Rijndael.
            case CryptoProvider.Rijndael:
                Rijndael rijndael = new RijndaelManaged();
                switch (cAction)
                {
                case CryptoAction.Encrypt:
                    transform = rijndael.CreateEncryptor(Key, IV);
                    break;

                case CryptoAction.Desencrypt:
                    transform = rijndael.CreateDecryptor(Key, IV);
                    break;
                }
                return(transform);

            default:
                // en caso que no exista el proveedor seleccionado, generamos
                // una excepción para informarlo.
                throw new CryptographicException("Error al inicializar al proveedor de cifrado");
            }
        }
Exemplo n.º 48
0
        public static string Encrypt(string originalString)
        {
            bool   flag = originalString == null || originalString.Trim() == "";
            string result;

            if (flag)
            {
                result = "";
            }
            else
            {
                try
                {
                    DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
                    MemoryStream             memoryStream             = new MemoryStream();
                    CryptoStream             cryptoStream             = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(Util.bytes, Util.bytes), CryptoStreamMode.Write);
                    StreamWriter             streamWriter             = new StreamWriter(cryptoStream);
                    streamWriter.Write(originalString);
                    streamWriter.Flush();
                    cryptoStream.FlushFinalBlock();
                    streamWriter.Flush();
                    result = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
                }
                catch (Exception)
                {
                    result = "";
                }
            }
            return(result);
        }
Exemplo n.º 49
0
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
        public static string DES_Encrypt(string encryptString, string encryptKey)
        {
            string result;

            try
            {
                byte[] bytes  = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] keys   = Keys;
                byte[] bytes2 = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dEsCryptoServiceProvider = new DESCryptoServiceProvider();
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, dEsCryptoServiceProvider.CreateEncryptor(bytes, keys), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytes2, 0, bytes2.Length);
                        cryptoStream.FlushFinalBlock();
                    }
                    result = Convert.ToBase64String(memoryStream.ToArray());
                }
            }
            catch
            {
                result = encryptString;
            }
            return(result);
        }
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
        public string EncryptDES(string encryptString, string encryptKey, bool defaultKey)
        {
            try
            {
                //对称算法实现的必须继承的抽象类
                SymmetricAlgorithm sa;
                //加密转化运算
                ICryptoTransform ct;
                //IO内存流
                MemoryStream ms;
                CryptoStream cs;
                byte[]       byt;

                //sa.Mode = CipherMode.CBC;

                sa         = new DESCryptoServiceProvider();
                sa.KeySize = 64;
                sa.Padding = PaddingMode.PKCS7;
                sa.Mode    = CipherMode.ECB;
                if (defaultKey)
                {
                    sa.Key = ConvertStringToByteArray(_defaultKey);
                    sa.IV  = ConvertStringToByteArray(_defaultKey);
                }
                else
                {
                    sa.Key = ConvertStringToByteArray(encryptKey);
                    sa.IV  = ConvertStringToByteArray(encryptKey);
                }
                ct = sa.CreateEncryptor();

                byt = ConvertStringToByteArray(encryptString);

                ms = new MemoryStream();
                cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                cs.Close();
                return(Convert.ToBase64String(ms.ToArray()));
            }
            catch (Exception e)
            {
                return("");
            }

            //try
            //{
            //    byte[] rgbKey;
            //    if (defaultKey)
            //    {
            //        rgbKey = Encoding.UTF8.GetBytes(_defaultKey);
            //    }
            //    else
            //    {
            //        rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
            //    }
            //    byte[] rgbIV = Keys;
            //    byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            //    DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
            //    MemoryStream mStream = new MemoryStream();
            //    CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            //    cStream.Write(inputByteArray, 0, inputByteArray.Length);
            //    cStream.FlushFinalBlock();
            //    return Convert.ToBase64String(mStream.ToArray());
            //}
            //catch (Exception ex)
            //{
            //    return encryptString;
            //}
        }
Exemplo n.º 51
0
        /// <summary>
        /// 加密。
        /// </summary>
        /// <param name="m_Need_Encode_String"></param>
        /// <returns></returns>
        public static string Encode(string m_Need_Encode_String)
        {
            if (m_Need_Encode_String == null)
            {
                throw new ArgumentNullException(nameof(m_Need_Encode_String));
            }
            DESCryptoServiceProvider objDES          = new DESCryptoServiceProvider();
            MemoryStream             objMemoryStream = new MemoryStream();
            CryptoStream             objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateEncryptor(arrDESKey, arrDESIV), CryptoStreamMode.Write);
            StreamWriter             objStreamWriter = new StreamWriter(objCryptoStream);

            objStreamWriter.Write(m_Need_Encode_String);
            objStreamWriter.Flush();
            objCryptoStream.FlushFinalBlock();
            objMemoryStream.Flush();
            objDES.Dispose();
            objMemoryStream.Dispose();
            objCryptoStream.Dispose();
            objStreamWriter.Dispose();
            return(Convert.ToBase64String(objMemoryStream.GetBuffer(), 0, (int)objMemoryStream.Length));
        }
Exemplo n.º 52
0
    /// <summary>
    /// DES加密字符串
    /// </summary>
    /// <param name="encryptString">待加密的字符串</param>
    /// <param name="encryptKey">加密密钥,要求为8位</param>
    // <returns>加密成功返回加密后的字符串,失败返回源串</returns>
    public static string DESEncrypt(this string cryptString, string key, string iv = "")
    {
        if (string.IsNullOrEmpty(iv))
        {
            iv = key;
        }
        byte[]                   bytes                    = SocketSecret._DESEncoding.GetBytes(cryptString);
        MemoryStream             memoryStream             = new MemoryStream();
        DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
        CryptoStream             cryptoStream             = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(SocketSecret._DESEncoding.GetBytes(key), SocketSecret._DESEncoding.GetBytes(iv)), CryptoStreamMode.Write);

        cryptoStream.Write(bytes, 0, bytes.Length);
        cryptoStream.FlushFinalBlock();
        return(Convert.ToBase64String(memoryStream.ToArray()));
    }
Exemplo n.º 53
0
        /// <summary>
        ///  DES加密
        /// </summary>
        public static string Encode(string str)
        {
            if (str == null)
            {
                throw new Exception("Error: \n源字符串为空!!");
            }
            DESCryptoServiceProvider objDES          = new DESCryptoServiceProvider();
            MemoryStream             objMemoryStream = new MemoryStream();
            CryptoStream             objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateEncryptor(arrDESKey, arrDESIV), CryptoStreamMode.Write);
            StreamWriter             objStreamWriter = new StreamWriter(objCryptoStream);

            objStreamWriter.Write(str);
            objStreamWriter.Flush();
            objCryptoStream.FlushFinalBlock();
            objMemoryStream.Flush();
            return(Convert.ToBase64String(objMemoryStream.GetBuffer(), 0, (int)objMemoryStream.Length));
        }
Exemplo n.º 54
0
        public static string BellaCiao(string helpme, int op)
        {
            if (op == 1)
            {
                // cifrado de la mderda
                string ToReturn = "";
                string _key     = "ay$a5%&jwrtmnh;lasjdf98787OMGFORLAX";
                string _iv      = "abc@98797hjkas$&asd(*$%GJMANIGE";
                byte[] _ivByte  = { };
                _ivByte = System.Text.Encoding.UTF8.GetBytes(_iv.Substring(0, 8));
                byte[] _keybyte = { };
                _keybyte = System.Text.Encoding.UTF8.GetBytes(_key.Substring(0, 8));
                MemoryStream ms = null; CryptoStream cs = null;
                byte[]       inputbyteArray = System.Text.Encoding.UTF8.GetBytes(helpme);
                using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
                {
                    ms = new MemoryStream();
                    cs = new CryptoStream(ms, des.CreateEncryptor(_keybyte, _ivByte), CryptoStreamMode.Write);
                    cs.Write(inputbyteArray, 0, inputbyteArray.Length);
                    cs.FlushFinalBlock();
                    ToReturn = Convert.ToBase64String(ms.ToArray());

                    var sb    = new StringBuilder();
                    var bytes = Encoding.UTF8.GetBytes(ToReturn);
                    foreach (var t in bytes)
                    {
                        sb.Append(t.ToString("X2"));
                    }
                    ToReturn = sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
                }
                return(ToReturn);
            }
            else
            {
                string ToReturn = "";
                string _key     = "ay$a5%&jwrtmnh;lasjdf98787OMGFORLAX";
                string _iv      = "abc@98797hjkas$&asd(*$%GJMANIGE";
                byte[] _ivByte  = { };
                _ivByte = System.Text.Encoding.UTF8.GetBytes(_iv.Substring(0, 8));
                byte[] _keybyte = { };
                _keybyte = System.Text.Encoding.UTF8.GetBytes(_key.Substring(0, 8));
                MemoryStream ms = null; CryptoStream cs = null;

                var bytes = new byte[helpme.Length / 2];
                for (var i = 0; i < bytes.Length; i++)
                {
                    bytes[i] = Convert.ToByte(helpme.Substring(i * 2, 2), 16);
                }
                helpme = Encoding.UTF8.GetString(bytes);
                byte[] inputbyteArray = new byte[helpme.Replace(" ", "+").Length];
                inputbyteArray = Convert.FromBase64String(helpme.Replace(" ", "+"));
                using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
                {
                    ms = new MemoryStream();
                    cs = new CryptoStream(ms, des.CreateDecryptor(_keybyte, _ivByte), CryptoStreamMode.Write);
                    cs.Write(inputbyteArray, 0, inputbyteArray.Length);
                    cs.FlushFinalBlock();
                    Encoding encoding = Encoding.UTF8;
                    ToReturn = encoding.GetString(ms.ToArray());
                }
                return(ToReturn);
            }
        }
Exemplo n.º 55
0
    // used to append the playing player and score from the datascript script to the online encrypted highscores.txt file
    public static void AppendStringToFile(string fileName, string plainText, byte[] key, byte[] iv)
    {
        using (var algo = new DESCryptoServiceProvider())
        {
            algo.Key = key;
            // The IV is set below
            algo.Mode    = CipherMode.CBC;
            algo.Padding = PaddingMode.PKCS7;

            // Create the streams used for encryption.
            using (FileStream file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                byte[] previous       = null;
                int    previousLength = 0;

                long length = file.Length;

                // No check is done that the file is correct!
                if (length != 0)
                {
                    // The IV length is equal to the block length
                    byte[] block = new byte[iv.Length];

                    if (length >= iv.Length * 2)
                    {
                        // At least 2 blocks, take the penultimate block
                        // as the IV
                        file.Position = length - iv.Length * 2;
                        file.Read(block, 0, block.Length);
                        algo.IV = block;
                    }
                    else
                    {
                        // A single block present, use the IV given
                        file.Position = length - iv.Length;
                        algo.IV       = iv;
                    }

                    // Read the last block
                    file.Read(block, 0, block.Length);

                    // And reposition at the beginning of the last block
                    file.Position = length - iv.Length;

                    // We use a MemoryStream because the CryptoStream
                    // will close the Stream at the end
                    using (var ms = new MemoryStream(block))
                        // Create a decrytor to perform the stream transform.
                        using (ICryptoTransform decryptor = algo.CreateDecryptor())
                            using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                            {
                                // Read all data from the stream. The decrypted last
                                // block can be long up to block length characters
                                // (so up to iv.Length) (this with AES + CBC)
                                previous       = new byte[iv.Length];
                                previousLength = cs.Read(previous, 0, previous.Length);
                            }
                }
                else
                {
                    // Use the IV given
                    algo.IV = iv;
                }

                // Create an encryptor to perform the stream transform
                using (ICryptoTransform encryptor = algo.CreateEncryptor())
                    using (CryptoStream cs = new CryptoStream(file, encryptor, CryptoStreamMode.Write))
                        using (StreamWriter sw = new StreamWriter(cs))
                        {
                            // Rewrite the last block, if present. We even skip
                            // the case of block present but empty
                            if (previousLength != 0)
                            {
                                cs.Write(previous, 0, previousLength);
                            }

                            // Write all data to the stream
                            sw.Write(System.Environment.NewLine);
                            sw.Write(plainText);
                            sw.Close();
                        }
            }
        }
    }
Exemplo n.º 56
0
        //Encryption Decryption code refrence: http://msdn.microsoft.com/en-us/library/system.security.cryptography.descryptoserviceprovider(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
        // Encrypt File Method taken from MSDN (customized, added exceptions)
        private void Encrypt()
        {
            // execute the code in a try block to catch necessary exceptions.
            try
            {
                // Variables needed to encrypt from user entry
                string inName  = this.path;
                string outName = this.path + ".des";

                // throw manual exception if no key is entered so the code breaks
                if (this.keyText.Text == "")
                {
                    throw new Exception("Please enter a key.");
                }
                if (!needsOverwrite(outName)) // Check to see if the file already exists and if user doesn't want to overwrite
                {
                    throw new IOException("File not overwritten.");
                    // Else continue and overwrite
                }
                // Use the method for the turining string into byteArray to get bytes
                byte[] desKey = this.byteArray();
                byte[] desIV  = this.byteArray();

                //Create the file streams to handle the input and output files.
                FileStream fin  = new FileStream(inName, FileMode.Open, FileAccess.Read);
                FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

                //Create variables to help with read and write.
                byte[] bin    = new byte[100];  //This is intermediate storage for the encryption.
                long   rdlen  = 0;              //This is the total number of bytes written.
                long   totlen = fin.Length;     //This is the total length of the input file.
                int    len;                     //This is the number of bytes to be written at a time.

                DES          des       = new DESCryptoServiceProvider();
                CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

                Console.WriteLine("Encrypting...");

                //Read from the input file, then encrypt and write to the output file.
                while (rdlen < totlen)
                {
                    len = fin.Read(bin, 0, 100);
                    encStream.Write(bin, 0, len);
                    rdlen = rdlen + len;
                    Console.WriteLine("{0} bytes processed", rdlen);
                }

                encStream.Close();
                fout.Close();
                fin.Close();
                Console.WriteLine("Done.");
            }
            //  If something in the try block throws an expections, catch here.
            catch (Exception e)
            {
                if (e is System.IO.FileNotFoundException)
                {
                    MessageBox.Show("Could not open source or destination file",
                                    "Error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1);
                }
                else if (e is System.Security.Cryptography.CryptographicException)
                {
                    MessageBox.Show("Bad key or file.",
                                    "Error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1);
                }
                else // This is the custon exception that is sent if manual exception is thrown
                {
                    MessageBox.Show(e.Message,
                                    "Error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1);
                }
            }
        }
Exemplo n.º 57
0
        public void GetBytes(byte[] buffer)
        {
            int n = buffer.Length;

            switch (_gammaId)
            {
            case GammaId.None:
                Array.Clear(buffer, 0, n);
                break;

            case GammaId.Aes:
                using (Aes aes = Aes.Create())
                {
                    Arcfour.SetKey(_key);
                    if (aes != null)
                    {
                        aes.Key = new byte[(aes.KeySize + BitsPerByte - 1) / BitsPerByte];
                        aes.IV  = new byte[(aes.BlockSize + BitsPerByte - 1) / BitsPerByte];
                        Arcfour.Prga(aes.Key);
                        Arcfour.Prga(aes.IV);
                        aes.Mode    = CipherMode.CBC;
                        aes.Padding = PaddingMode.Zeros;

                        // Create a decrytor to perform the stream transform.
                        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                        // Create the streams used for encryption.
                        using (var memoryStream = new MemoryStream())
                        {
                            using (
                                var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
                                )
                            {
                                try
                                {
                                    //Write all data to the stream.
                                    cryptoStream.Write(Enumerable.Repeat(FillByte, n).ToArray(), 0, n);
                                    cryptoStream.FlushFinalBlock();
                                }
                                catch
                                {
                                }
                            }
                            // Return the encrypted bytes from the memory stream.
                            Array.Copy(memoryStream.ToArray(), buffer, n);
                        }
                    }
                }
                break;

            case GammaId.Des:
                using (var serviceProvider = new DESCryptoServiceProvider())
                {
                    Arcfour.SetKey(_key);
                    serviceProvider.Key = new byte[(serviceProvider.KeySize + BitsPerByte - 1) / BitsPerByte];
                    serviceProvider.IV  = new byte[(serviceProvider.BlockSize + BitsPerByte - 1) / BitsPerByte];
                    Arcfour.Prga(serviceProvider.Key);
                    Arcfour.Prga(serviceProvider.IV);
                    serviceProvider.Mode    = CipherMode.CBC;
                    serviceProvider.Padding = PaddingMode.Zeros;

                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform encryptor = serviceProvider.CreateEncryptor(serviceProvider.Key,
                                                                                 serviceProvider.IV);

                    // Create the streams used for encryption.
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            try
                            {
                                //Write all data to the stream.
                                cryptoStream.Write(Enumerable.Repeat(FillByte, n).ToArray(), 0, n);
                                cryptoStream.FlushFinalBlock();
                            }
                            catch
                            {
                            }
                        }
                        // Return the encrypted bytes from the memory stream.
                        Array.Copy(memoryStream.ToArray(), buffer, n);
                    }
                }
                break;

            case GammaId.TripleDes:
                using (var serviceProvider = new TripleDESCryptoServiceProvider())
                {
                    Arcfour.SetKey(_key);
                    serviceProvider.Key = new byte[(serviceProvider.KeySize + BitsPerByte - 1) / BitsPerByte];
                    serviceProvider.IV  = new byte[(serviceProvider.BlockSize + BitsPerByte - 1) / BitsPerByte];
                    Arcfour.Prga(serviceProvider.Key);
                    Arcfour.Prga(serviceProvider.IV);
                    serviceProvider.Mode    = CipherMode.CBC;
                    serviceProvider.Padding = PaddingMode.Zeros;

                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform encryptor = serviceProvider.CreateEncryptor(serviceProvider.Key,
                                                                                 serviceProvider.IV);

                    // Create the streams used for encryption.
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            try
                            {
                                //Write all data to the stream.
                                cryptoStream.Write(Enumerable.Repeat(FillByte, n).ToArray(), 0, n);
                                cryptoStream.FlushFinalBlock();
                            }
                            catch
                            {
                            }
                        }
                        // Return the encrypted bytes from the memory stream.
                        Array.Copy(memoryStream.ToArray(), buffer, n);
                    }
                }
                break;

            case GammaId.Arcfour:
                Arcfour.SetKey(_key);
                Arcfour.Prga(buffer);
                break;

            default:
                throw new NotImplementedException();
            }
        }
Exemplo n.º 58
0
        /// <summary>
        /// Encrypt ScopedPdu using DES encryption protocol
        /// </summary>
        /// <param name="unencryptedData">Unencrypted ScopedPdu byte array</param>
        /// <param name="key">Encryption key. Key has to be at least 32 bytes is length</param>
        /// <param name="privacyParameters">Privacy parameters out buffer. This field will be filled in with information
        /// required to decrypt the information. Output length of this field is 8 bytes and space has to be reserved
        /// in the USM header to store this information</param>
        /// <returns>Encrypted byte array</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key is null or length of the encryption key is too short.</exception>
        public static byte[] Encrypt(byte[] unencryptedData, byte[] key, byte[] privacyParameters)
        {
            if (unencryptedData == null)
            {
                throw new ArgumentNullException("unencryptedData");
            }

            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (privacyParameters == null)
            {
                throw new ArgumentNullException("privacyParameters");
            }

            if (key.Length < MinimumKeyLength)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Encryption key length has to 32 bytes or more. Current: {0}", key.Length), "key");
            }

            var iv = GetIV(key, privacyParameters);

            // DES uses 8 byte keys but we need 16 to encrypt ScopedPdu. Get first 8 bytes and use them as encryption key
            var outKey = GetKey(key);

            var div = (int)Math.Floor(unencryptedData.Length / 8.0);

            if ((unencryptedData.Length % 8) != 0)
            {
                div += 1;
            }

            var newLength = div * 8;
            var result    = new byte[newLength];
            var buffer    = new byte[newLength];

            var inbuffer   = new byte[8];
            var cipherText = iv;
            var posIn      = 0;
            var posResult  = 0;

            Buffer.BlockCopy(unencryptedData, 0, buffer, 0, unencryptedData.Length);

            using (DES des = new DESCryptoServiceProvider())
            {
                des.Mode    = CipherMode.ECB;
                des.Padding = PaddingMode.None;

                using (var transform = des.CreateEncryptor(outKey, null))
                {
                    for (var b = 0; b < div; b++)
                    {
                        for (var i = 0; i < 8; i++)
                        {
                            inbuffer[i] = (byte)(buffer[posIn] ^ cipherText[i]);
                            posIn++;
                        }

                        transform.TransformBlock(inbuffer, 0, inbuffer.Length, cipherText, 0);
                        Buffer.BlockCopy(cipherText, 0, result, posResult, cipherText.Length);
                        posResult += cipherText.Length;
                    }
                }

                des.Clear();
            }

            return(result);
        }
Exemplo n.º 59
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        private string GetUserInfo()
        {
            string str = "";
            ManagementObjectCollection instances = new ManagementClass("Win32_Processor").GetInstances();

            foreach (ManagementObject obj2 in instances)
            {
                str = obj2.Properties["ProcessorId"].Value.ToString();
                break;
            }
            ManagementObjectCollection objects2 = new ManagementClass("win32_logicaldisk").GetInstances();

            foreach (ManagementObject obj3 in objects2)
            {
                if (obj3["DeviceID"].ToString() == "C:")
                {
                    str = str + obj3["VolumeSerialNumber"].ToString();
                    break;
                }
            }
            ManagementObjectCollection objects3 = new ManagementClass("Win32_NetworkAdapterConfiguration").GetInstances();

            foreach (ManagementObject obj2 in objects3)
            {
                if ((bool)obj2["IPEnabled"])
                {
                    str = str + obj2["MacAddress"].ToString();
                    break;
                }
            }
            str = str.Replace(":", "");
            int length = str.Length / 3;

            str = str.Substring(0, length) + str;
            str = str.Substring(str.Length - length, length) + str;
            str = str.Remove(str.Length - length, length);
            int    num3 = str.Length;
            string s    = "";

            for (int i = 0; i < num3; i++)
            {
                s = str.Substring(i, 1) + s;
            }
            s = "DIB93" + s + "83LDO";
            byte[] buffer  = new byte[] { 0x13, 9, 20, 6, 7, 1, 5, 8 };
            byte[] buffer2 = new byte[] { 0x16, 9, 20, 0x15, 7, 1, 5, 8 };
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            byte[] bytes = Encoding.Default.GetBytes(s);
            provider.Key = buffer;
            provider.IV  = buffer2;
            MemoryStream stream  = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            StringBuilder builder = new StringBuilder();

            foreach (byte num5 in stream.ToArray())
            {
                builder.AppendFormat("{0:X2}", num5);
            }
            return(this.getSysTime(builder.ToString()));
        }
Exemplo n.º 60
0
        //加密
        public static string DESEncrypt(string data)
        {
            byte[] key = new byte[]
            {
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8
            };
            byte[] iv = new byte[]
            {
                8,
                7,
                6,
                5,
                4,
                3,
                2,
                1
            };
            MemoryStream memoryStream = null;
            CryptoStream cryptoStream = null;
            StreamWriter streamWriter = null;
            string       result       = string.Empty;

            try
            {
                DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                int i = cryptoProvider.KeySize;
                memoryStream = new MemoryStream();
                cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, iv),
                                                CryptoStreamMode.Write);
                streamWriter = new StreamWriter(cryptoStream);
                streamWriter.Write(data);
                streamWriter.Flush();
                cryptoStream.FlushFinalBlock();
                streamWriter.Flush();
                result = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                }
                if (cryptoStream != null)
                {
                    cryptoStream.Close();
                }
                if (memoryStream != null)
                {
                    memoryStream.Close();
                }
            }
            return(result);
        }