コード例 #1
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 "";
		}

	}
コード例 #2
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();
    }
コード例 #3
0
ファイル: test.cs プロジェクト: 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;
	}
コード例 #4
0
ファイル: DES.cs プロジェクト: RushHang/H_DataAssembly
 /// <summary>
 /// 对文件内容进行DES解密
 /// </summary>
 /// <param name="sourceFile">待解密的文件绝对路径</param>
 /// <param name="destFile">解密后的文件保存的绝对路径</param>
 public static void DecryptFile(string sourceFile, string destFile)
 {
     if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在!", sourceFile);
     byte[] btKey = Encoding.Default.GetBytes(key);
     byte[] btIV = Encoding.Default.GetBytes(iv);
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     byte[] btFile = File.ReadAllBytes(sourceFile);
     using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
     {
         try
         {
             using (CryptoStream cs = new CryptoStream(fs, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
             {
                 cs.Write(btFile, 0, btFile.Length);
                 cs.FlushFinalBlock();
             }
         }
         catch
         {
             throw;
         }
         finally
         {
             fs.Close();
         }
     }
 }
コード例 #5
0
    public bool TryDecrypt(string encryptedItem, string password, out string decryptedItem)
    {
        if (string.IsNullOrEmpty (encryptedItem) ||
            string.IsNullOrEmpty (password)) {
            decryptedItem = "";
            return false;
        }

        try {
            byte[] cipherBytes = Convert.FromBase64String (encryptedItem);

            using (var memoryStream = new MemoryStream(cipherBytes)) {
                var des = new DESCryptoServiceProvider ();

                byte[] iv = new byte[8];
                memoryStream.Read (iv, 0, iv.Length);

                var rfc2898DeriveBytes = new Rfc2898DeriveBytes (password, iv, ITERATIONS);

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

                using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream)) {
                    decryptedItem = streamReader.ReadToEnd ();
                    return true;
                }
            }
        } catch (Exception ex) {
            Logger.instance.Log (new Logger.Message (this, ex));

            decryptedItem = "";
            return false;
        }
    }
コード例 #6
0
ファイル: CryptionManager.cs プロジェクト: IanWendy/IanTools
    private string DeCryption(string content, string sKey, string sIV)
    {
        try
        {
            byte[] inputByteArray = Convert.FromBase64String(content);
            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                //byte[] inputByteArray = Convert.FromBase64String(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.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    //cs.Clear();
                    cs.Write(inputByteArray,0,inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }

                string str = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
        catch
        {
            return "String Not Base64 Encode!!!";
        }
    }
コード例 #7
0
ファイル: SaveData.cs プロジェクト: Niklas83/UnityGame1
	public static SaveData Load()
	{
		if (!File.Exists("save01.sav"))
			return null;
			
		SaveData data = null;
		using(Stream stream = File.Open("save01.sav", FileMode.Open)) {
			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.CreateDecryptor(byKey, dv), CryptoStreamMode.Read))
				{
					Log.debug("Save", "Loading...");
					try {
						data = (SaveData) binaryFormatter.Deserialize(cryptoStream);
					} catch (Exception e) {
						Log.debug("Save", ""+e);
						return new SaveData();
					}
					Log.debug("Save", "Loaded (level={0})", data.level);
					cryptoStream.Close();
				}
			}
			stream.Close();
		}
		return data;
	}
コード例 #8
0
    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 ());
            }
        }
    }
コード例 #9
0
ファイル: CookiesHelper.cs プロジェクト: qq5013/JXNG
    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();
    }
コード例 #10
0
ファイル: Cipher.cs プロジェクト: Vinhbaba/dskfeorfqlhvsea
    //cmThe function used to decrypt the text
    private static string Decrypt(string strText, string SaltKey)
    {
        byte[] byKey = { };
        byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
        byte[] inputByteArray = new byte[strText.Length + 1];

        try
        {
            byKey = System.Text.Encoding.UTF8.GetBytes(SaltKey.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(strText);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

            return encoding.GetString(ms.ToArray());

        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
コード例 #11
0
ファイル: CookiesHelper.cs プロジェクト: qq5013/JXNG
    public static string Decrypt(string originalString, string sKey)
    {
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        byte[] inputByteArray = new byte[originalString.Length / 2];
        for (int x = 0; x < originalString.Length / 2; x++)
        {
            int i = (Convert.ToInt32(originalString.Substring(x * 2, 2), 16));
            inputByteArray[x] = (byte)i;
        }

        //建立加密对象的密钥和偏移量,此值重要,不能修改

        des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);

        des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();

        //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
        StringBuilder ret = new StringBuilder();

        return System.Text.Encoding.Default.GetString(ms.ToArray());
    }
コード例 #12
0
        /// <summary>
        /// 对数据进行解密
        /// </summary>
        /// <param name="decryptstring">需要解密的数据</param>
        /// <returns></returns>
        public static string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            try
            {
                DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                MemoryStream ms = new MemoryStream(byEnc);
                CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
                StreamReader sr = new StreamReader(cst);
                return sr.ReadToEnd();
            }
            catch
            {
                return null;
            }

        }
コード例 #13
0
ファイル: Utils.cs プロジェクト: trantrung2608/ilinkbay
 public static string Decrypt(string stringToDecrypt)
 {
     string sEncryptionKey = "thuynnxkey";
     byte[] key = { };
     byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
     byte[] inputByteArray = new byte[stringToDecrypt.Length];
     try
     {
         key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         inputByteArray = Convert.FromBase64String(stringToDecrypt);
         MemoryStream ms = new MemoryStream();
         CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         cs.Close();
         Encoding encoding = Encoding.UTF8;
         return encoding.GetString(ms.ToArray());
     }
     catch (System.Exception ex)
     {
         SiAuto.Main.LogString("Lỗi :", ex.ToString());
         return (string.Empty);
     }
 }
コード例 #14
0
ファイル: Program1.cs プロジェクト: Makk24/GetHtmlPage
 // 加密字符串
 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);
 }
コード例 #15
0
ファイル: Encryptor.cs プロジェクト: eamelaram/prueba
 public string Decrypt(string SourceData)
 {
     byte[] EncryptedDataBytes = Convert.FromBase64String(SourceData);
     MemoryStream TempStream = new MemoryStream(EncryptedDataBytes, 0, EncryptedDataBytes.Length);
     DESCryptoServiceProvider Decryptor = new DESCryptoServiceProvider();
     CryptoStream DecryptionStream = new CryptoStream(TempStream, Decryptor.CreateDecryptor(Key, Iv), CryptoStreamMode.Read);
     StreamReader AllDataReader = new StreamReader(DecryptionStream);
     return AllDataReader.ReadToEnd();
 }
コード例 #16
0
 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, 1};
     Byte[]  IV = {0, 0, 0, 0, 0, 0, 0, 0};
     DESCryptoServiceProvider     des = new DESCryptoServiceProvider();
     des.Key = Key;
     
     return false;
 }
コード例 #17
0
ファイル: FFCrypto.cs プロジェクト: protonate/csharp_sample1
 public static string DESDecrypt(string input)
 {
     byte[] bytes = Encoding.ASCII.GetBytes((string)ConfigurationSettings.AppSettings["CipherKeyProd"]);
     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
     MemoryStream memoryStream = new MemoryStream
             (Convert.FromBase64String(input));
     CryptoStream cryptoStream = new CryptoStream(memoryStream,
         cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
     StreamReader reader = new StreamReader(cryptoStream);
     return reader.ReadToEnd();
 }
コード例 #18
0
ファイル: DBOperations.cs プロジェクト: vatsal/Stoocker
    public string Decrypt(string input)
    {
        string output = "";

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(input));
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(cryptBytes, cryptBytes), CryptoStreamMode.Read);
        StreamReader reader = new StreamReader(cryptoStream);

        output = reader.ReadToEnd();
        return output;
    }
コード例 #19
0
ファイル: DESzh.cs プロジェクト: ZH0322/ZOUKE
    /**/
    /// <summary>
    /// 对称加密解密的密钥
    /// </summary>
    public static string Key
    {
        get
        {
            return key;
        }
        set
        {
            key = value;
        }
    }

    #endregion Properties

    #region Methods

    /**/
    /// <summary>
    /// DES解密
    /// </summary>
    /// <param name="decryptString"></param>
    /// <returns></returns>
    public static string DesDecrypt(string decryptString)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
        byte[] keyIV = keyBytes;
        byte[] inputByteArray = Convert.FromBase64String(decryptString);
        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
        cStream.Write(inputByteArray, 0, inputByteArray.Length);
        cStream.FlushFinalBlock();
        return Encoding.UTF8.GetString(mStream.ToArray());
    }
コード例 #20
0
ファイル: Encryptor.cs プロジェクト: eamelaram/prueba
 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));
 }
コード例 #21
0
    //by me
    public string Decrypt(string oldword)
    {
        if (String.IsNullOrEmpty(oldword))
        {
            throw new ArgumentNullException("The string which needs to be decrypted can not be null.");
        }

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(oldword));
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
        StreamReader reader = new StreamReader(cryptoStream);
        return reader.ReadToEnd();
    }
コード例 #22
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());
 }
コード例 #23
0
 public static string DecryptDES(string text, byte[] key)
 {
     if(text != null && text != "")
     {
         DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
         MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(text));
         CryptoStream cryptoStream = new CryptoStream(memoryStream,
                 cryptoProvider.CreateDecryptor(key, key), CryptoStreamMode.Read);
         StreamReader reader = new StreamReader(cryptoStream);
         text = reader.ReadToEnd();
     }
     return text;
 }
コード例 #24
0
ファイル: FFCrypto.cs プロジェクト: protonate/csharp_sample1
 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);
 }
コード例 #25
0
    public static string SimplyDecrypt(string encryptedContent)
    {
        var result = string.Empty;

        var des = new DESCryptoServiceProvider();
        var decryptor = des.CreateDecryptor(Encoding.ASCII.GetBytes(Secret), Encoding.ASCII.GetBytes(IV));

        var dataToDec = Convert.FromBase64String(encryptedContent);
        var resultBytes = decryptor.TransformFinalBlock(dataToDec, 0, dataToDec.Length);

        result = Encoding.UTF8.GetString(resultBytes);

        return result;
    }
コード例 #26
0
    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;
    }
コード例 #27
0
ファイル: Encryption.cs プロジェクト: jonezy/ProductSite
    /// <summary>
    /// Standard DES decryption
    /// </summary>
    /// <param name="val">Value of decrypted</param>
    /// <returns>Returns decrypted value as string</returns>
    public static string Decrypt(string val)
    {
        string decrpted = "";
        if (val != "") {
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

            //convert from string to byte
            byte[] buffer = Convert.FromBase64String(val);
            MemoryStream ms = new MemoryStream(buffer);
            CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_64, IV_64), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            decrpted = sr.ReadToEnd();
        }
        return decrpted;
    }
コード例 #28
0
ファイル: CryptoHelper.cs プロジェクト: JFox-sk/EPayment
    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;
    }
コード例 #29
0
ファイル: Program1.cs プロジェクト: Makk24/GetHtmlPage
 // 解密字符串
 public string DecryptString(string sInputString, string sKey)
 {
     string[] sInput = sInputString.Split("-".ToCharArray());
     var data = new byte[sInput.Length];
     for (int i = 0; i < sInput.Length; i++)
     {
         data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
     }
     var DES = new DESCryptoServiceProvider();
     DES.Key = Encoding.ASCII.GetBytes(sKey);
     DES.IV = Encoding.ASCII.GetBytes(sKey);
     ICryptoTransform desencrypt = DES.CreateDecryptor();
     byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
     return Encoding.UTF8.GetString(result);
 }
コード例 #30
0
ファイル: Login.aspx.cs プロジェクト: yangpeiren/hello-world
    public static string GetMD5HashHex(String input)
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        DES des = new DESCryptoServiceProvider();
        byte[] res = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input), 0, input.Length);

        String returnThis = "";

        for (int i = 0; i < res.Length; i++)
        {
            returnThis += System.Uri.HexEscape((char)res[i]);
        }
        returnThis = returnThis.Replace("%", "");
        returnThis = returnThis.ToLower();
        return returnThis;
    }
コード例 #31
0
        public string Decrypt(string strKey, string strData)
        {
            if (strData == "")
            {
                return("");
            }

            string strValue = "";

            if (!String.IsNullOrEmpty(strKey))
            {
                // convert key to 16 characters for simplicity
                int ii = strKey.Length;
                if (ii < 16)
                {
                    strKey = strKey + "XXXXXXXXXXXXXXXX".Substring(0, 16 - strKey.Length);
                }
                else if (ii > 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 and Base64 decode
                byte[] byteData = new byte[strData.Length + 1];
                try
                {
                    byteData = Convert.FromBase64String(strData);
                }
                catch // invalid length
                {
                    strValue = strData;
                }

                if (strValue == "")
                {
                    try
                    {
                        // decrypt
                        DESCryptoServiceProvider objDES          = new DESCryptoServiceProvider();
                        MemoryStream             objMemoryStream = new MemoryStream();
                        CryptoStream             objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write);
                        objCryptoStream.Write(byteData, 0, byteData.Length);
                        objCryptoStream.FlushFinalBlock();

                        // convert to string
                        Encoding objEncoding = Encoding.UTF8;
                        strValue = objEncoding.GetString(objMemoryStream.ToArray());
                    }
                    catch // decryption error
                    {
                        strValue = "";
                    }
                }
            }
            else
            {
                strValue = strData;
            }

            return(strValue);
        }
コード例 #32
0
        public static string Enkriptimi(string name, string message, string user)
        {
            string s = "C:\\Users\\Lenovo\\Desktop\\Detyra1_DS-Gr-6-master\\ds\\bin\\Debug\\netcoreapp3.0\\keys\\" + name + ".pub.pem";

            byte[] bytePlaintext =
                Encoding.UTF8.GetBytes(message);

            RSACryptoServiceProvider rsaPublic = new RSACryptoServiceProvider();

            Chilkat.PublicKey pubKey2 = new Chilkat.PublicKey();
            pubKey2.LoadOpenSslPemFile(s);
            string pubKeyXml = pubKey2.GetXml();


            rsaPublic.FromXmlString(pubKeyXml);

            DESCryptoServiceProvider FjalaDES =
                new DESCryptoServiceProvider();

            byte[] keyRandom = GenerateKey();
            byte[] keyIV     = GenerateIv();
            FjalaDES.Key     = keyRandom;
            FjalaDES.IV      = keyIV;
            FjalaDES.Mode    = CipherMode.CBC;
            FjalaDES.Padding = PaddingMode.PKCS7;


            // FjalaDES.Key = Encoding.UTF8.GetBytes("12345678");
            // FjalaDES.IV = Encoding.UTF8.GetBytes("12345678");
            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms,
                                               FjalaDES.CreateEncryptor(),
                                               CryptoStreamMode.Write);

            cs.Write(bytePlaintext, 0, bytePlaintext.Length);
            cs.FlushFinalBlock();

            cs.Close();

            byte[] byteCiphertexti = ms.ToArray();



            // mesazhi i koduar nga celsi des
            string ciphertexti = Convert.ToBase64String(byteCiphertexti);

            // celsi des i koduar permes celsit rsa
            byte[] encryptedRSA = rsaPublic.Encrypt(keyRandom, false);
            string ciphertexti1 = Convert.ToBase64String(encryptedRSA);

            //Kodimi i emrit te celsit
            byte[] emriVarg     = Formovargun(name);
            string ciphertexti2 = Convert.ToBase64String(emriVarg);
            //kodimi i iv
            string ciphertexti3 = Convert.ToBase64String(FjalaDES.IV);

            //pjesa e 3
            byte[] signedData   = Sign.HashAndSignBytes(byteCiphertexti, user);
            string ciphertexti5 = Convert.ToBase64String(signedData);
            string ciphertexti4 = Convert.ToBase64String(Formovargun(user));


            string total = ciphertexti2 + "." + ciphertexti3 + "." + ciphertexti1 +
                           "." + ciphertexti + ciphertexti4 + ciphertexti5;

            // Console.WriteLine(ciphertexti);
            return(total);
        }
コード例 #33
0
ファイル: Program.cs プロジェクト: A-tafaj/ds2020_gr13
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                string command = args[0];

                RsaEncryptor  rsa;
                DirectoryInfo di = Directory.CreateDirectory(@"../../../keys/");

                if (command == "create-user")
                {
                    try
                    {
                        if (args[1].Length != 0)
                        {
                            string        command2 = args[1];
                            StringBuilder sb       = new StringBuilder();
                            for (int i = 0; i < command2.Length; i++)
                            {
                                if ((command2[i] >= '0' && command2[i] <= '9') || (command2[i] >= 'A' && command2[i] <= 'Z') || (command2[i] >= 'a' && command2[i] <= 'z') || command2[i] == '_')
                                {
                                    sb.Append(command2[i].ToString());
                                }
                                else
                                {
                                    Console.WriteLine("Emrat duhet të përmbajnë vetëm simbolet A-Z, a-z, 0-9,dhe _");
                                    return;
                                }
                            }
                            command2 = sb.ToString();
                            rsa      = new RsaEncryptor();
                            string privateKey = rsa.GetPrivateKey();
                            string publicKey  = rsa.GetPublicKey();
                            string privkey    = di + command2 + ".xml";
                            string pubkey     = di + command2 + ".pub.xml";
                            if (File.Exists(privkey) && File.Exists(pubkey))
                            {
                                Console.WriteLine("Gabim: Celesi '" + command2 + "' ekziston paraprakisht.");
                                return;
                            }
                            File.WriteAllText(di + command2 + ".xml", privateKey);
                            File.WriteAllText(di + command2 + ".pub.xml", publicKey);

                            Console.WriteLine("Eshte krijuar celsi privat: 'keys/{0}.xml'", command2);
                            Console.WriteLine("Eshte krijuar celsi publik: 'keys/{0}.pub.xml'", command2);
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Kerkesa duhet te jete: create-user <emri>");
                        return;
                    }
                }

                else if (command == "delete-user")
                {
                    try
                    {
                        if (args[1].Length != 0)
                        {
                            string        command2 = args[1];
                            StringBuilder sb       = new StringBuilder();
                            for (int i = 0; i < command2.Length; i++)
                            {
                                if ((command2[i] >= '0' && command2[i] <= '9') || (command2[i] >= 'A' && command2[i] <= 'Z') || (command2[i] >= 'a' && command2[i] <= 'z') || command2[i] == '_')
                                {
                                    sb.Append(command2[i].ToString());
                                }
                                else
                                {
                                    Console.WriteLine("Emrat duhet të përmbajnë vetëm simbolet A-Z, a-z, 0-9,dhe _");
                                    return;
                                }
                            }
                            command2 = sb.ToString();
                            rsa      = new RsaEncryptor();
                            string privateKey = rsa.GetPrivateKey();
                            string publicKey  = rsa.GetPublicKey();
                            string privkey    = di + command2 + ".xml";
                            string pubkey     = di + command2 + ".pub.xml";
                            if (File.Exists(privkey) && File.Exists(pubkey))
                            {
                                File.Delete(privkey);
                                File.Delete(pubkey);
                                Console.WriteLine("Eshte larguar celsi privat: 'keys/{0}.xml'", command2);
                                Console.WriteLine("Eshte larguar celsi publik: 'keys/{0}.pub.xml'", command2);
                            }
                            else
                            {
                                Console.WriteLine("Gabim: Celesi '" + command2 + "' nuk ekziston.");
                            }
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Kerkesa duhet te jete: delete-user <emri>");
                        return;
                    }
                }
                else if (command == "export-key")
                {
                    try
                    {
                        if (args[1].Length != 0 && args[2].Length != 0)
                        {
                            string type = args[1];
                            string name = args[2];
                            //DirectoryInfo dir = Directory.CreateDirectory("keys/");
                            //We have di for directory $top.
                            string privKeysDir = /*dir*/ di + name + ".xml";
                            string pubKeysDir  = /*dir*/ di + name + ".pub.xml";
                            if (File.Exists(pubKeysDir) && File.Exists(privKeysDir))
                            {
                                if (args.Length == 3)
                                {
                                    /*if (type == "public")
                                     * {
                                     *  string publicKey = File.ReadAllText(di + name + ".pub.xml");
                                     *  char[] seperator = { '>' };
                                     *  String[] strlist = publicKey.Split(seperator);
                                     *  foreach(String s in strlist){Console.Write(s + ">"); Console.WriteLine();}
                                     *
                                     * }*/
                                    if (type == "public")
                                    {
                                        string publicKey = File.ReadAllText(/*dir*/ di + name + ".pub.xml");
                                        publicKey = publicKey.Replace(">", ">" + System.Environment.NewLine);
                                        Console.WriteLine("\n" + publicKey + "\n");
                                    }
                                    else if (type == "private")
                                    {
                                        string privateKey = File.ReadAllText(/*dir*/ di + name + ".xml");
                                        privateKey = privateKey.Replace(">", ">" + System.Environment.NewLine);
                                        Console.WriteLine("\n" + privateKey + "\n");
                                    }
                                }
                                else if (args.Length == 4 /*> 3*/)
                                {
                                    string        expFile = args[3];
                                    DirectoryInfo expDir  = Directory.CreateDirectory("exported/");
                                    using (StreamWriter strw = File.CreateText(expDir + expFile));
                                    string publicKey = File.ReadAllText(/*dir*/ di + name + ".pub.xml");//
                                    File.WriteAllText(expDir + expFile, publicKey);
                                    Console.WriteLine("Celesi publik u ruajt ne fajllin " + expFile + ".xml");
                                }
                            }
                            else if (File.Exists(pubKeysDir) && !File.Exists(privKeysDir))
                            {
                                if (args.Length == 3)
                                {
                                    if (type == "public")
                                    {
                                        string publicKey = File.ReadAllText(/*dir*/ di + name + ".pub.xml");
                                        Console.WriteLine("\n" + publicKey + "\n");
                                    }
                                    else if (type == "private")
                                    {
                                        //string privateKey = File.ReadAllText(/*dir*/ di + name + ".xml");
                                        Console.WriteLine("\nGabim: Celesi privat " + name + " nuk ekziston\n");
                                    }
                                }
                                else if (args.Length == 4 /*> 3*/)
                                {
                                    string        expFile = args[3];
                                    DirectoryInfo expDir  = Directory.CreateDirectory("exported/");
                                    using (StreamWriter strw = File.CreateText(expDir + expFile));
                                    string publicKey = File.ReadAllText(/*dir*/ di + name + ".pub.xml");//
                                    File.WriteAllText(expDir + expFile, publicKey);
                                    Console.WriteLine("Celesi publik u ruajt ne fajllin " + expFile);
                                }
                            }
                            else
                            {
                                Console.WriteLine("Gabim: Celesi publik " + name + " nuk ekziston.");
                            }
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Kerkesa duhet te jete: export-key <public|private> <name> dhe [file] opsionale");
                    }
                }

                else if (command == "list-keys")//Komande shtese -> listimi i celesave (needs to convert from path name > name:)
                {
                    Dictionary <string, string> list_keys = new Dictionary <string, string>();
                    string[] fCount = Directory.GetFiles(@"../../../keys/", "*.xml");

                    foreach (string k in fCount)
                    {
                        string val = File.ReadAllText(@k, Encoding.UTF8);
                        list_keys.Add(k, val);
                    }
                    foreach (KeyValuePair <string, string> item in list_keys)
                    {
                        Console.WriteLine("Key: {0}, \nValue: {1}\n\n", item.Key, item.Value);
                    }
                }

                else if (command == "write-message")
                {
                    string input = args[1];

                    string pubkey = di + input + ".pub.xml";
                    DESCryptoServiceProvider objDes = new DESCryptoServiceProvider();

                    string randKey = Convert.ToBase64String(objDes.Key);
                    string randiv  = Convert.ToBase64String(objDes.IV);


                    if (File.Exists(pubkey))
                    {
                        if (args.Length == 3)
                        {
                            string publicKey = File.ReadAllText(di + input + ".pub.xml");
                            string tekst     = args[2];

                            Console.WriteLine(WR.Base64Encode(input) + "." + WR.Base64Encode(randiv) + "." + WR.rsa_Encrypt(randKey, publicKey) + "." + WR.des_Encrypt(tekst, randKey, randiv));
                        }
                        else if (args.Length == 4)
                        {
                            string        publicKey = File.ReadAllText(di + input + ".pub.xml");
                            string        tekst     = args[2];
                            string        file      = args[3];
                            DirectoryInfo di2       = Directory.CreateDirectory(@"../../../files/");
                            using (StreamWriter sw = File.CreateText(di2 + file));

                            string g = ("\n" + WR.Base64Encode(input) + "." + WR.Base64Encode(randiv) + "." + WR.rsa_Encrypt(randKey, publicKey) + "." + WR.des_Encrypt(tekst, randKey, randiv));
                            File.WriteAllText(di2 + file, g);

                            Console.WriteLine("Mesazhi i enkriptuar u ruajt ne fajllin: files/{0}", file);
                        }
                        else
                        {
                            Console.WriteLine("Numri i argumenteve nuk eshte valid!");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Celesi publik: {0} nuk ekziston ", input);
                    }
                }
                else if (command == "read-message")
                {
                    string cipher = args[1];
                    var    array  = cipher.Split(new[] { '.' }, 4);

                    string firstElem = array[0];
                    string second    = array[1];
                    string third     = array[2];
                    string fourth    = array[3];
                    if (WR.Check_Base64(firstElem) && WR.Check_Base64(second) && WR.Check_Base64(third) && WR.Check_Base64(fourth))
                    {
                        string input   = WR.Base64Decode(firstElem);
                        string privkey = di + input + ".xml";

                        if (File.Exists(privkey))
                        {
                            Console.WriteLine("Marresi: " + input);
                            string privateKey = File.ReadAllText(di + input + ".xml");
                            try
                            {
                                string iv_get = WR.Base64Decode(second);
                                try
                                {
                                    string rsaKey_get = WR.rsa_Decrypt(third, privateKey);
                                    try
                                    {
                                        Console.WriteLine("Dekriptimi: " + WR.des_Decrypt(fourth, rsaKey_get, iv_get));
                                    }
                                    catch (Exception)
                                    {
                                        Console.WriteLine("Error: {0}");
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Error: {0}", e);
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Error: {0}", e);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Celesi privat " + input + " nuk ekziston.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Nuk eshte Base64!");
                    }
                }
                //FAZA 1
                else if (command == "four-square")
                {
                    try
                    {
                        if (args[1] == "encrypt")
                        {
                            try
                            {
                                string plaintext = args[2];
                                string key1      = args[3];
                                string key2      = args[4];
                                Console.WriteLine("Encryption: " + FS.Encrypt(plaintext, key1, key2));
                            }

                            catch (Exception)
                            {
                                Console.WriteLine("You should put arguments in this order: <plaintext> <key1> <key2>" +
                                                  "\nIf plaintext is a sentence, put them in \"\", key must be one word and contain only letters!");
                            }
                        }
                        else if (args[1] == "decrypt")
                        {
                            try
                            {
                                string ciphertext = args[2];
                                string key1       = args[3];
                                string key2       = args[4];
                                Console.WriteLine("Decryption: " + FS.Decrypt(ciphertext, key1, key2));
                            }

                            catch (Exception)
                            {
                                Console.WriteLine("You should put arguments in this order: <ciphertext> <key1> <key2>");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Your command should be: <encrypt> or <decrypt> ");
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("COMMANDS: <encrypt> <decrypt>");
                    }
                }

                else if (command == "case")
                {
                    try
                    {
                        if (args[1] == "lower")
                        {
                            string word = args[2];
                            Console.WriteLine(word.ToLower());
                        }
                        else if (args[1] == "upper")
                        {
                            string word = args[2];
                            Console.WriteLine(word.ToUpper());
                        }
                        else if (args[1] == "capitalize")
                        {
                            string word = args[2];
                            Console.WriteLine(CASE.Capitalize(word));
                        }
                        else if (args[1] == "inverse")
                        {
                            string word = args[2];
                            Console.WriteLine(CASE.Inverse(word));
                        }
                        else if (args[1] == "alternating")
                        {
                            string word = args[2];
                            Console.WriteLine(CASE.Alternating(word));
                        }
                        else if (args[1] == "sentence")
                        {
                            string a = args[2];
                            Console.Write(a.ToLower() + ", " + CASE.Str2(a) + ". " + a.ToUpper() + "! " + CASE.Str4(a) + ".\n" + CASE.Str5(a) + ", " + a.ToLower() + ". " + CASE.Str7(a) + "! " + CASE.Str8(a) + ".");
                        }
                        else
                        {
                            Console.WriteLine("Your command was wrong, choice one of the cases: <lower> <upper> <capitalize> <inverse> <alternating> <sentence>");
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("CASES: <lower> <upper> <capitalize> <inverse> <alternating> <sentence> ");
                    }
                }
                else if (command == "rail-fence")
                {
                    try
                    {
                        if (args[1] == "encrypt")
                        {
                            string plaint  = args[2];
                            string rail    = args[3];
                            int    railsNr = Int32.Parse(rail);
                            Console.WriteLine(RF.Rencode(plaint, railsNr));
                        }
                        else if (args[1] == "decrypt")
                        {
                            string ciphert = args[2];
                            string rail    = args[3];
                            int    railsNr = Int32.Parse(rail);
                            Console.WriteLine(RF.Rdecode(ciphert, railsNr));
                        }
                        else
                        {
                            Console.WriteLine("You must choose beetwen: <encrypt> <decrypt>");
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Continue: <plaintext> <rails>");
                    }
                }
                else
                {
                    Console.WriteLine("Kerkesa duhet te jete: <create-user> <delete-user> <write-message> <read-message>");
                }

                /*else
                 *              {
                 *                      Console.WriteLine("You should provide a valid METHOD: <four-square> <case> <rail-fence>");
                 *              }*/
            }
        }
コード例 #34
0
 public EncryptionService()
 {
     _provider   = new DESCryptoServiceProvider();
     _key        = Encoding.Default.GetBytes("MyKeyCaS");
     _initVector = Encoding.Default.GetBytes("itVector");
 }
コード例 #35
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 (Exception e)
     {
         throw new Exception("加密数据出错,详细原因:" + e.Message);
     }
 }
コード例 #36
0
        //---------------------------------------------------------------------
        public static SymmetricAlgorithm Create_SymmetricAlgorithm(SymmetricAlgorithms SymmetricAlgorithm_in, byte[] PasswordBytes_in)
        {
            HashAlgorithm      HA = Create_HashAlgorithm(HashAlgorithms.SHA_512);
            SymmetricAlgorithm SA = null;

            switch (SymmetricAlgorithm_in)
            {
            case SymmetricAlgorithms.None:
                return(null);

            case SymmetricAlgorithms.Unused_1:
                return(null);

            case SymmetricAlgorithms.RC2_64_40:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 40;
                break;

            case SymmetricAlgorithms.RC2_64_48:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 48;
                break;

            case SymmetricAlgorithms.RC2_64_56:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 56;
                break;

            case SymmetricAlgorithms.RC2_64_64:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 64;
                break;

            case SymmetricAlgorithms.RC2_64_72:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 72;
                break;

            case SymmetricAlgorithms.RC2_64_80:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 80;
                break;

            case SymmetricAlgorithms.RC2_64_88:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 88;
                break;

            case SymmetricAlgorithms.RC2_64_96:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 96;
                break;

            case SymmetricAlgorithms.RC2_64_104:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 104;
                break;

            case SymmetricAlgorithms.RC2_64_112:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 112;
                break;

            case SymmetricAlgorithms.RC2_64_120:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 120;
                break;

            case SymmetricAlgorithms.RC2_64_128:
                SA           = new RC2CryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 128;
                break;

            case SymmetricAlgorithms.DES_64_64:
                SA           = new DESCryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 64;
                break;

            case SymmetricAlgorithms.DES3_64_128:
                SA           = new TripleDESCryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 128;
                break;

            case SymmetricAlgorithms.DES3_64_192:
                SA           = new TripleDESCryptoServiceProvider();
                SA.BlockSize = 64;
                SA.KeySize   = 192;
                break;

            case SymmetricAlgorithms.AES_128_128:
                SA           = new RijndaelManaged();
                SA.BlockSize = 128;
                SA.KeySize   = 128;
                break;

            case SymmetricAlgorithms.AES_128_192:
                SA           = new RijndaelManaged();
                SA.BlockSize = 128;
                SA.KeySize   = 192;
                break;

            case SymmetricAlgorithms.AES_128_256:
                SA           = new RijndaelManaged();
                SA.BlockSize = 128;
                SA.KeySize   = 256;
                break;

            case SymmetricAlgorithms.AES_192_128:
                SA           = new RijndaelManaged();
                SA.BlockSize = 192;
                SA.KeySize   = 128;
                break;

            case SymmetricAlgorithms.AES_192_192:
                SA           = new RijndaelManaged();
                SA.BlockSize = 192;
                SA.KeySize   = 192;
                break;

            case SymmetricAlgorithms.AES_192_256:
                SA           = new RijndaelManaged();
                SA.BlockSize = 192;
                SA.KeySize   = 256;
                break;

            case SymmetricAlgorithms.AES_256_128:
                SA           = new RijndaelManaged();
                SA.BlockSize = 256;
                SA.KeySize   = 128;
                break;

            case SymmetricAlgorithms.AES_256_192:
                SA           = new RijndaelManaged();
                SA.BlockSize = 256;
                SA.KeySize   = 192;
                break;

            case SymmetricAlgorithms.AES_256_256:
                SA           = new RijndaelManaged();
                SA.BlockSize = 256;
                SA.KeySize   = 256;
                break;

            default:
                return(null);
            }
            SA.Key = Create_CryptographicKey(HashAlgorithms.SHA_256, SA.KeySize, PasswordBytes_in);
            SA.IV  = Create_CryptographicIV(HashAlgorithms.SHA_256, SA.BlockSize, PasswordBytes_in);
            return(SA);
        }
コード例 #37
0
 public override void Visit(MyFile file)
 {
     if (crypt)
     {
         using (FileStream fin = file.FileOpen(FileMode.Open, FileAccess.Read, FileShare.None))
         {
             MyFile cryptedFile = Factory.CreateFile(file.FullPath + "_crypted");
             using (FileStream fout = cryptedFile.FileOpen(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
             {
                 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();
                 using (CryptoStream encStream = new CryptoStream(fout, desProvider.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write))
                 {
                     //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;
                     }
                 }
             }
         }
         file.Delete();
     }
     else
     {
         bool success = true;
         using (FileStream fin = file.FileOpen(FileMode.Open, FileAccess.Read, FileShare.None))
         {
             MyFile decryptedFile;
             string pathToCryptedFile = file.FullPath;
             if (pathToCryptedFile.EndsWith("_crypted"))
             {
                 decryptedFile = Factory.CreateFile(file.FullPath.Remove(pathToCryptedFile.Length - "_crypted".Length));
             }
             else
             {
                 decryptedFile = Factory.CreateFile(pathToCryptedFile + "_decrypted");
             }
             using (FileStream fout = decryptedFile.FileOpen(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
             {
                 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();
                 try
                 {
                     using (CryptoStream encStream = new CryptoStream(fout, desProvider.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write))
                     {
                         //Read from the input file, then decrypt and write to the output file.
                         while (rdlen < totlen)
                         {
                             len = fin.Read(bin, 0, 100);
                             encStream.Write(bin, 0, len);
                             rdlen = rdlen + len;
                         }
                     }
                 }
                 catch (CryptographicException exc)
                 {
                     System.Windows.Forms.MessageBox.Show(exc.Message + "Неверный ключ.");
                     success = false;
                 }
                 catch (IOException ioexc)
                 {
                     System.Windows.Forms.MessageBox.Show(ioexc.Message + "Ошибка доступа.");
                 }
                 catch (Exception exc)
                 {
                     System.Windows.Forms.MessageBox.Show(exc.Message + "Неопознанная ошибка.");
                 }
             }
             if (!success)
             {
                 decryptedFile.Delete();
             }
         }
         if (success)
         {
             file.Delete();
         }
     }
 }
コード例 #38
0
ファイル: Class25.cs プロジェクト: nghieppv/SimpleUID
        // Token: 0x06000089 RID: 137 RVA: 0x00009840 File Offset: 0x00007A40
        internal static byte[] smethod_4(long long_0, Stream stream_0)
        {
            Stream       stream       = stream_0;
            MemoryStream memoryStream = null;

            for (int i = 1; i < 4; i++)
            {
                stream_0.ReadByte();
            }
            int num = (ushort)stream_0.ReadByte();

            num = ~num;
            if ((num & 2) != 0)
            {
                DESCryptoServiceProvider descryptoServiceProvider = new DESCryptoServiceProvider();
                byte[] array = new byte[8];
                stream_0.Read(array, 0, 8);
                descryptoServiceProvider.IV = array;
                byte[] array2 = new byte[8];
                stream_0.Read(array2, 0, 8);
                bool   flag   = true;
                byte[] array3 = array2;
                for (int j = 0; j < array3.Length; j++)
                {
                    if (array3[j] != 0)
                    {
                        flag = false;
IL_8B:
                        if (flag)
                        {
                            array2 = Class25.smethod_1(Assembly.GetExecutingAssembly());
                        }
                        descryptoServiceProvider.Key = array2;
                        if (Class25.memoryStream_0 == null)
                        {
                            if (Class25.int_0 == 2147483647)
                            {
                                Class25.memoryStream_0.Capacity = (int)stream_0.Length;
                            }
                            else
                            {
                                Class25.memoryStream_0.Capacity = Class25.int_0;
                            }
                        }
                        Class25.memoryStream_0.Position = 0L;
                        ICryptoTransform cryptoTransform = descryptoServiceProvider.CreateDecryptor();
                        int    inputBlockSize            = cryptoTransform.InputBlockSize;
                        int    outputBlockSize           = cryptoTransform.OutputBlockSize;
                        byte[] array4 = new byte[cryptoTransform.OutputBlockSize];
                        byte[] array5 = new byte[cryptoTransform.InputBlockSize];
                        int    num2   = (int)stream_0.Position;
                        while ((long)(num2 + inputBlockSize) < stream_0.Length)
                        {
                            stream_0.Read(array5, 0, inputBlockSize);
                            int count = cryptoTransform.TransformBlock(array5, 0, inputBlockSize, array4, 0);
                            Class25.memoryStream_0.Write(array4, 0, count);
                            num2 += inputBlockSize;
                        }
                        stream_0.Read(array5, 0, (int)(stream_0.Length - (long)num2));
                        byte[] array6 = cryptoTransform.TransformFinalBlock(array5, 0, (int)(stream_0.Length - (long)num2));
                        Class25.memoryStream_0.Write(array6, 0, array6.Length);
                        stream          = Class25.memoryStream_0;
                        stream.Position = 0L;
                        memoryStream    = Class25.memoryStream_0;
                        goto IL_1C6;
                    }
                }
                //goto IL_8B;
            }
IL_1C6:
            if ((num & 8) != 0)
            {
                if (Class25.memoryStream_1 == null)
                {
                    if (Class25.int_1 == -2147483648)
                    {
                        Class25.memoryStream_1.Capacity = (int)stream.Length * 2;
                    }
                    else
                    {
                        Class25.memoryStream_1.Capacity = Class25.int_1;
                    }
                }
                Class25.memoryStream_1.Position = 0L;
                DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress);
                int           num3          = 1000;
                byte[]        buffer        = new byte[1000];
                int           num4;
                do
                {
                    num4 = deflateStream.Read(buffer, 0, num3);
                    if (num4 > 0)
                    {
                        Class25.memoryStream_1.Write(buffer, 0, num4);
                    }
                }while (num4 >= num3);
                memoryStream = Class25.memoryStream_1;
            }
            if (memoryStream != null)
            {
                return(memoryStream.ToArray());
            }
            byte[] array7 = new byte[stream_0.Length - stream_0.Position];
            stream_0.Read(array7, 0, array7.Length);
            return(array7);
        }
コード例 #39
0
        internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            // Pick the provider.
            switch (algorithmID)
            {
            case EncryptionAlgorithm.Des:
            {
                DES des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;

                // See if a key was provided
                if (null == bytesKey)
                {
                    encKey = des.Key;
                }
                else
                {
                    des.Key = bytesKey;
                    encKey  = des.Key;
                }
                // See if the client provided an initialization vector
                if (null == initVec)
                {                         // Have the algorithm create one
                    initVec = des.IV;
                }
                else
                {                         //No, give it to the algorithm
                    des.IV = initVec;
                }
                return(des.CreateEncryptor());
            }

            case EncryptionAlgorithm.TripleDes:
            {
                TripleDES des3 = new TripleDESCryptoServiceProvider();
                des3.Mode = CipherMode.CBC;
                // See if a key was provided
                if (null == bytesKey)
                {
                    encKey = des3.Key;
                }
                else
                {
                    des3.Key = bytesKey;
                    encKey   = des3.Key;
                }
                // See if the client provided an IV
                if (null == initVec)
                {                         //Yes, have the alg create one
                    initVec = des3.IV;
                }
                else
                {                         //No, give it to the alg.
                    des3.IV = initVec;
                }
                return(des3.CreateEncryptor());
            }

            case EncryptionAlgorithm.Rc2:
            {
                RC2 rc2 = new RC2CryptoServiceProvider();
                rc2.Mode = CipherMode.CBC;
                // Test to see if a key was provided
                if (null == bytesKey)
                {
                    encKey = rc2.Key;
                }
                else
                {
                    rc2.Key = bytesKey;
                    encKey  = rc2.Key;
                }
                // See if the client provided an IV
                if (null == initVec)
                {                         //Yes, have the alg create one
                    initVec = rc2.IV;
                }
                else
                {                         //No, give it to the alg.
                    rc2.IV = initVec;
                }
                return(rc2.CreateEncryptor());
            }

            case EncryptionAlgorithm.Rijndael:
            {
                Rijndael rijndael = new RijndaelManaged();
                rijndael.Mode = CipherMode.CBC;
                // Test to see if a key was provided
                if (null == bytesKey)
                {
                    encKey = rijndael.Key;
                }
                else
                {
                    rijndael.Key = bytesKey;
                    encKey       = rijndael.Key;
                }
                // See if the client provided an IV
                if (null == initVec)
                {                         //Yes, have the alg create one
                    initVec = rijndael.IV;
                }
                else
                {                         //No, give it to the alg.
                    rijndael.IV = initVec;
                }
                return(rijndael.CreateEncryptor());
            }

            default:
            {
                throw new CryptographicException("Algorithm ID '" +
                                                 algorithmID +
                                                 "' not supported.");
            }
            }
        }
コード例 #40
0
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Decrypt(string text, string sKey)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException(text);
            }
            if (string.IsNullOrEmpty(sKey))
            {
                throw new ArgumentNullException(sKey);
            }
            MemoryStream             ms  = null;
            DESCryptoServiceProvider des = null;

            try
            {
                des = new DESCryptoServiceProvider();
                var    len            = text.Length / 2;
                byte[] inputByteArray = new byte[len];
                int    x;
                for (x = 0; x < len; x++)
                {
                    var i = Convert.ToInt32(text.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }
                var bKey = Encoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8));
                des.Key = bKey;
                des.IV  = bKey;
                ms      = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return(Encoding.Default.GetString(ms.ToArray()));
            }
            catch (NotSupportedException nsex)
            {
                throw nsex;
            }
            catch (ArgumentNullException arnex)
            {
                throw arnex;
            }
            catch (EncoderFallbackException efex)
            {
                throw efex;
            }
            catch (ArgumentException arex)
            {
                throw arex;
            }
            catch (CryptographicException crex)
            {
                throw crex;
            }
            finally
            {
                if (ms != null)
                {
                    ms.Close();
                }
                if (des != null)
                {
                    des.Clear();
                }
            }
        }
コード例 #41
0
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Encrypt(string text, string sKey)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException(text);
            }
            if (string.IsNullOrEmpty(sKey))
            {
                throw new ArgumentNullException(sKey);
            }
            MemoryStream             ms  = null;
            DESCryptoServiceProvider des = null;

            try
            {
                des = new DESCryptoServiceProvider();
                var inputByteArray = Encoding.Default.GetBytes(text);
                var bKey           = Encoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8));
                des.Key = bKey;
                des.IV  = bKey;
                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);
                }
                return(ret.ToString());
            }
            catch (NotSupportedException nsex)
            {
                throw nsex;
            }
            catch (ArgumentNullException arnex)
            {
                throw arnex;
            }
            catch (EncoderFallbackException efex)
            {
                throw efex;
            }
            catch (ArgumentException arex)
            {
                throw arex;
            }
            catch (CryptographicException crex)
            {
                throw crex;
            }
            finally
            {
                if (ms != null)
                {
                    ms.Close();
                }
                if (des != null)
                {
                    des.Clear();
                }
            }
        }
コード例 #42
0
 public DES()
     : base()
 {
     algorithm = new DESCryptoServiceProvider();
 }
コード例 #43
0
        /// <summary>
        /// 对加密密文进行解密

        /// </summary>
        /// <param name="encryptText">待解密的密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文字符串</returns>
        public static string DecryptStringReverse(string encryptText, string key)
        {
            string result = "";

            if (string.IsNullOrEmpty(encryptText))
            {
                return(result);
            }

            try
            {
                //如无,取默认值

                string keyStr = string.IsNullOrEmpty(key) ? VariableName.DefaultEncryptKey : key;

                //密文
                byte[] encData = System.Convert.FromBase64String(encryptText);

                //将密文写入内存

                MemoryStream sin = new MemoryStream(encData);

                MemoryStream sout = new MemoryStream();

                DES des = new DESCryptoServiceProvider();

                //得到密钥
                string sTemp;
                if (des.LegalKeySizes.Length > 0)
                {
                    int lessSize = 0, moreSize = des.LegalKeySizes[0].MinSize;

                    while (keyStr.Length * 8 > moreSize &&
                           des.LegalKeySizes[0].SkipSize > 0 &&
                           moreSize < des.LegalKeySizes[0].MaxSize)
                    {
                        lessSize  = moreSize;
                        moreSize += des.LegalKeySizes[0].SkipSize;
                    }

                    if (keyStr.Length * 8 > moreSize)
                    {
                        sTemp = keyStr.Substring(0, (moreSize / 8));
                    }
                    else
                    {
                        sTemp = keyStr.PadRight(moreSize / 8, ' ');
                    }
                }
                else
                {
                    sTemp = keyStr;
                }

                //设置密钥
                des.Key = ASCIIEncoding.ASCII.GetBytes(sTemp);


                //设置初始化向量

                if (keyStr.Length > des.IV.Length)
                {
                    des.IV = ASCIIEncoding.ASCII.GetBytes(keyStr.Substring(0, des.IV.Length));
                }
                else
                {
                    des.IV = ASCIIEncoding.ASCII.GetBytes(keyStr.PadRight(des.IV.Length, ' '));
                }

                //解密流

                CryptoStream decStream = new CryptoStream(sin, des.CreateDecryptor(), CryptoStreamMode.Read);

                //密文流的长度
                long lLen = sin.Length;
                //已经读取长度
                int nReadTotal = 0;

                //读入块

                byte[] buf = new byte[8];

                int nRead;

                //从密文流读到解密流中
                while (nReadTotal < lLen)
                {
                    nRead = decStream.Read(buf, 0, buf.Length);
                    if (0 == nRead)
                    {
                        break;
                    }

                    sout.Write(buf, 0, nRead);
                    nReadTotal += nRead;
                }
                decStream.Close();

                //明文
                //ASCIIEncoding ascEnc = new ASCIIEncoding();
                UnicodeEncoding ascEnc = new UnicodeEncoding();
                result = ascEnc.GetString(sout.ToArray());
            }
            catch { }

            return(result);
        }
コード例 #44
0
ファイル: SecurityHelper.cs プロジェクト: puxu1989/PXLib
        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="filePath">输入文件路径</param>
        /// <param name="savePath">解密后输出文件路径</param>
        /// <param name="keyStr">密码,可以为“”/NULL</param>
        /// <returns></returns>
        public static bool FileDecrypt(string filePathName, string savePathName, string keyStr)
        {
            FileStream               fs  = null;
            MemoryStream             ms  = null;
            CryptoStream             cs  = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            if (string.IsNullOrEmpty(keyStr))
            {
                keyStr = defFilesEncryptKey;
            }
            try
            {
                fs = File.OpenRead(filePathName);
                byte[] inputByteArray = new byte[fs.Length];
                fs.Read(inputByteArray, 0, (int)fs.Length);
                fs.Close();
                byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
                SHA1   ha           = new SHA1Managed();
                byte[] hb           = ha.ComputeHash(keyByteArray);
                byte[] sKey         = new byte[8];
                byte[] sIV          = new byte[8];
                for (int i = 0; i < 8; i++)
                {
                    sKey[i] = hb[i];
                }
                for (int i = 8; i < 16; i++)
                {
                    sIV[i - 8] = hb[i];
                }
                des.Key = sKey;
                des.IV  = sIV;
                ms      = new MemoryStream();
                cs      = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                fs = File.OpenWrite(savePathName);
                foreach (byte b in ms.ToArray())
                {
                    fs.WriteByte(b);
                }
                return(true);
            }
            catch (Exception ex)
            {
                log.WriteLog(ex);
                return(false);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
                if (cs != null)
                {
                    cs.Close();
                }
                if (ms != null)
                {
                    ms.Close();
                }
            }
        }
コード例 #45
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);
        }
コード例 #46
0
        private CryptoStream DESCreateDecryptor(Stream fsread, string sKey)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

            return(new CryptoStream(fsread, DES.CreateDecryptor(), CryptoStreamMode.Read));
        }
コード例 #47
0
        private string AnahtarCalistirma()
        {
            DESCryptoServiceProvider kripto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

            return(ASCIIEncoding.ASCII.GetString(kripto.Key));
        }
コード例 #48
0
        public static void Main(string[] args)
        {
            // Mapping for files that require the use of custom IV strings
            var customFileIV = new System.Collections.Generic.Dictionary <string, string>()
            {
                { "CastleSiegeBuffRule.csv", "SiegeBuf" },
                { "CastleSiegeBuffRule_Name.csv", "SiegeBuf" },
                { "DialogGuide.csv", "Dialog.c" },
                { "EsportsConst.csv", "Const_eS" },
                { "FortressSiegeBuffRule.csv", "SiegeBuf" },
                { "FortressSiegeBuffRule_Name.csv", "SiegeBuf" },
                { "GuildAchievement.csv", "Achievem" },
                { "GuildAchievement_Name.csv", "Achievem" },
                { "HelpUrl.csv", "Help.csv" },
                { "HelpUrl_Name.csv", "Help.csv" },
                { "MissionDaily.csv", "Mission." },
                { "MissionDaily_Name.csv", "Mission." },
                { "MissionDailyReward.csv", "Mission." },
                { "MissionWeekly.csv", "Mission." },
                { "MissionWeekly_Name.csv", "Mission." },
                { "MissionWeeklyReward.csv", "Mission." },
                { "NpcSpawn.csv", "/NpcSpaw" },
                { "PetConditionString.csv", "Pet.csv" },
                { "PetExp.csv", "Pet.csv" },
                { "PetGrade.csv", "Pet.csv" },
                { "PromoteGrade.csv", "Promote." },
                { "Quest.csv", "/Quest/0" },
                { "Quest_Name.csv", "/Quest/0" },
                { "ServerString.csv", "String.c" },
                { "ServerString_Name.csv", "String.c" },
                { "ShopInApp.csv", "Shopinap" },
                { "ShopItem.csv", "Shop.csv" },
                { "ShopItem_Name.csv", "Shop.csv" },
                { "ShopItemProduct.csv", "ShopProd" },
                { "SlanderName.csv", "Slander." },
                { "SlanderMessage_Name.csv", "Slander." },
                { "UseableAchievementTask.csv", "Achievem" }
            };

            foreach (string filename in args)
            {
                Console.WriteLine("File: {0}", filename);

                byte[] fileData = System.IO.File.ReadAllBytes(filename);
                // Default the IV string to the filename.
                string unformattedIV = Path.GetFileName(filename);
                // Looks to find if there is an undersore in file name
                int offset = unformattedIV.IndexOf('_');
                // Override if there is a custom IV string
                // If not then will remove underscores and replace with .csv
                if (customFileIV.ContainsKey(unformattedIV))
                {
                    unformattedIV = customFileIV[unformattedIV];
                }
                else if (offset >= 0)
                {
                    unformattedIV = unformattedIV.Substring(0, offset) + ".csv";
                }


                byte[] fileIV = System.Text.Encoding.ASCII.GetBytes(unformattedIV.PadRight(8, '\0').Substring(0, 8));


                try
                {
                    using (DESCryptoServiceProvider provider = new DESCryptoServiceProvider())
                    {
                        provider.Key = DES_Key;
                        provider.IV  = fileIV;

                        ICryptoTransform crypto = provider.CreateDecryptor();

                        using (MemoryStream dataStream = new MemoryStream(fileData))
                            using (CryptoStream cryptStream = new CryptoStream(dataStream, crypto, CryptoStreamMode.Read))
                                using (StreamReader decryptedStream = new StreamReader(cryptStream))
                                {
                                    string outData = decryptedStream.ReadToEnd();

                                    string filePath = Path.GetDirectoryName(filename);
                                    string outPath  = Path.Combine(filePath, "Decrypted");
                                    if (!Directory.Exists(outPath))
                                    {
                                        Directory.CreateDirectory(outPath);
                                    }


                                    string outFile = Path.Combine(outPath, Path.GetFileName(filename));

                                    File.WriteAllText(outFile, outData);
                                }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                }
            }
        }
コード例 #49
0
        public string GenerateKey()
        {
            DESCryptoServiceProvider provider = (DESCryptoServiceProvider)DES.Create();

            return(Encoding.ASCII.GetString(provider.Key));
        }
コード例 #50
0
        private void btnGenerateKey_Click(object sender, EventArgs e)
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

            tbKey.Text = Convert.ToBase64String(desCrypto.Key);
        }
コード例 #51
0
        // 创建Key
        public static string GenerateKey()
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

            return(ASCIIEncoding.ASCII.GetString(desCrypto.Key));
        }
コード例 #52
0
        /// <summary> Function to encrypt an one content bytes
        /// </summary>
        /// <param name="content">Function to encrypt an one content bytes</param>
        /// <returns>Array of bytes</returns>
        public byte[] Encrypt(byte[] content)
        {
            if (!IsHashAlgorithm && _key == null)
            {
                throw new CryptographicException(Resources.Cypher_NoKey);
            }

            if (content == null || content.Equals(String.Empty))
            {
                throw new CryptographicException(Resources.Cypher_NoContent);
            }

            byte[] cipherBytes = null;
            int    NumBytes    = 0;

#if !CompactFramework
            if (_algorithm == Algorithm.RSA)
            {
                //This is an asymmetric call, which has to be treated differently
                cipherBytes = RSAEncrypt(content);
            }
            else
#endif
            if (IsHashAlgorithm)
            {
                string hash = GenerateHash(System.Text.Encoding.UTF8.GetString(content, 0, content.Length));
                cipherBytes = System.Text.Encoding.UTF8.GetBytes(hash);
            }
            else
            {
                SymmetricAlgorithm provider;
                switch (_algorithm)
                {
                case Algorithm.DES:
                    provider = new DESCryptoServiceProvider();
                    NumBytes = Convert.ToInt32(AlgorithmKeySize.DES);
                    break;

                case Algorithm.TripleDES:
                    provider = new TripleDESCryptoServiceProvider();
                    NumBytes = Convert.ToInt32(AlgorithmKeySize.TripleDES);
                    break;

                case Algorithm.Rijndael:
                    provider = new RijndaelManaged();
                    NumBytes = Convert.ToInt32(AlgorithmKeySize.Rijndael);
                    break;

                case Algorithm.RC2:
                    provider = new RC2CryptoServiceProvider();
                    NumBytes = Convert.ToInt32(AlgorithmKeySize.RC2);
                    break;

                default:
                    throw new CryptographicException(Resources.Cypher_InvalidProvider);
                }

                try
                {
                    //Encrypt the string
                    cipherBytes = SymmetricEncrypt(provider, content, _key, NumBytes);
                }
                finally
                {
                    //Free any resources held by the SymmetricAlgorithm provider
                    provider.Clear();
                }
            }
            return(cipherBytes);
        }
コード例 #53
0
        /// <summary> Function to decrypt an one content bytes
        /// </summary>
        /// <param name="content">To be encrypted content</param>
        /// <returns>Array of bytes</returns>
        public byte[] Decrypt(byte[] content)
        {
            if (IsHashAlgorithm)
            {
                throw new CryptographicException(Resources.Cypher_DecryptHash);
            }

            if (_key == null)
            {
                throw new CryptographicException(Resources.Cypher_NoKey);
            }

            if (content == null || content.Equals(String.Empty))
            {
                throw new CryptographicException(Resources.Cypher_NoContent);
            }

            string encText = System.Text.Encoding.UTF8.GetString(content, 0, content.Length);

            if (_encodingType == EncodingType.Base64)
            {
                //We need to convert the content to Hex before decryption
                encText = BytesToHex(System.Convert.FromBase64String(encText));
            }

            byte[] clearBytes = null;
            int    NumBytes   = 0;

#if !CompactFramework
            if (_algorithm == Algorithm.RSA)
            {
                clearBytes = RSADecrypt(encText);
            }
            else
#endif
            {
                SymmetricAlgorithm provider;
                switch (_algorithm)
                {
                case Algorithm.DES:
                    provider = new DESCryptoServiceProvider();
                    NumBytes = Convert.ToInt32(AlgorithmKeySize.DES);
                    break;

                case Algorithm.TripleDES:
                    provider = new TripleDESCryptoServiceProvider();
                    NumBytes = Convert.ToInt32(AlgorithmKeySize.TripleDES);
                    break;

                case Algorithm.Rijndael:
                    provider = new RijndaelManaged();
                    NumBytes = Convert.ToInt32(AlgorithmKeySize.Rijndael);
                    break;

                case Algorithm.RC2:
                    provider = new RC2CryptoServiceProvider();
                    NumBytes = Convert.ToInt32(AlgorithmKeySize.RC2);
                    break;

                default:
                    throw new CryptographicException(Resources.Cypher_InvalidProvider);
                }
                try
                {
                    clearBytes = SymmetricDecrypt(provider, encText, _key, NumBytes);
                }
                finally
                {
                    //Free any resources held by the SymmetricAlgorithm provider
                    provider.Clear();
                }
            }
            //Now return the plain text content
            return(clearBytes);
        }
コード例 #54
0
ファイル: MyDESAlgo.cs プロジェクト: IhorPetr/CryptoGraphy
 public MyDESAlgo()
 {
     this.myTripleDES = new DESCryptoServiceProvider();
 }
コード例 #55
0
        internal static byte[] cd28247e67c0c72bed8d3bd7d2f376ddb(long c94d7d3929ab24e50a1d9c5279e0ca34c, Stream c90e7c90ead6c95222c8a43ceed60a2b1)
        {
            Stream       stream       = c90e7c90ead6c95222c8a43ceed60a2b1;
            MemoryStream memoryStream = cb340211dab5e5cad862474535531b3fb.c20c00b8e97bb4c0fb2b7ac6facf98b91;

            for (int index = 1; index < 4; ++index)
            {
                c90e7c90ead6c95222c8a43ceed60a2b1.ReadByte();
            }
label_3:
            switch (3)
            {
            case 0:
                goto label_3;

            default:
                if (1 == 0)
                {
                    // ISSUE: method reference
                    RuntimeMethodHandle runtimeMethodHandle = __methodref(c9654c418e330d33bb3f6a61645043740.cd28247e67c0c72bed8d3bd7d2f376ddb);
                }
                ushort num1 = ~(ushort)c90e7c90ead6c95222c8a43ceed60a2b1.ReadByte();
                if (((int)num1 & 2) != 0)
                {
label_7:
                    switch (6)
                    {
                    case 0:
                        goto label_7;

                    default:
                        DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider();
                        byte[] buffer1 = cf6c44ce1629f394b5ef11499eb386125.c27c941905305b0ff3e7324bc79625bf4(8);
                        c90e7c90ead6c95222c8a43ceed60a2b1.Read(buffer1, 0, 8);
                        cryptoServiceProvider.IV = buffer1;
                        byte[] buffer2 = cf6c44ce1629f394b5ef11499eb386125.c27c941905305b0ff3e7324bc79625bf4(8);
                        c90e7c90ead6c95222c8a43ceed60a2b1.Read(buffer2, 0, 8);
                        bool   flag = true;
                        byte[] c33ad1bd311fd4b32b85377e9e15a9d93 = buffer2;
                        for (int index = 0; index < (int)c66a1c83bdee03fa41a70c643b5176698.c572aba370be49804cbdb0b35312bea94(c33ad1bd311fd4b32b85377e9e15a9d93); ++index)
                        {
                            if ((int)c33ad1bd311fd4b32b85377e9e15a9d93[index] != 0)
                            {
label_10:
                                switch (7)
                                {
                                case 0:
                                    goto label_10;

                                default:
                                    flag = false;
                                    goto label_15;
                                }
                            }
                        }
label_14:
                        switch (5)
                        {
                        case 0:
                            goto label_14;
                        }
label_15:
                        if (flag)
                        {
label_16:
                            switch (1)
                            {
                            case 0:
                                goto label_16;

                            default:
                                buffer2 = c9654c418e330d33bb3f6a61645043740.c1ddc000be9484a84934c477ccb3f8f34(Assembly.GetExecutingAssembly());
                                break;
                            }
                        }
                        cryptoServiceProvider.Key = buffer2;
                        if (c9654c418e330d33bb3f6a61645043740.cc894a1bd974202896bb4271f940b47ba == null)
                        {
label_19:
                            switch (6)
                            {
                            case 0:
                                goto label_19;

                            default:
                                if (c9654c418e330d33bb3f6a61645043740.c18393f272475a5a63e643687f7f9e4f2 == int.MaxValue)
                                {
label_21:
                                    switch (6)
                                    {
                                    case 0:
                                        goto label_21;

                                    default:
                                        c9654c418e330d33bb3f6a61645043740.cc894a1bd974202896bb4271f940b47ba.Capacity = (int)c90e7c90ead6c95222c8a43ceed60a2b1.Length;
                                        break;
                                    }
                                }
                                else
                                {
                                    c9654c418e330d33bb3f6a61645043740.cc894a1bd974202896bb4271f940b47ba.Capacity = c9654c418e330d33bb3f6a61645043740.c18393f272475a5a63e643687f7f9e4f2;
                                    break;
                                }
                            }
                        }
                        c9654c418e330d33bb3f6a61645043740.cc894a1bd974202896bb4271f940b47ba.Position = 0L;
                        ICryptoTransform decryptor = cryptoServiceProvider.CreateDecryptor();
                        int    inputBlockSize      = decryptor.InputBlockSize;
                        int    outputBlockSize     = decryptor.OutputBlockSize;
                        byte[] numArray1           = cf6c44ce1629f394b5ef11499eb386125.c27c941905305b0ff3e7324bc79625bf4(decryptor.OutputBlockSize);
                        byte[] numArray2           = cf6c44ce1629f394b5ef11499eb386125.c27c941905305b0ff3e7324bc79625bf4(decryptor.InputBlockSize);
                        int    position            = (int)c90e7c90ead6c95222c8a43ceed60a2b1.Position;
                        while ((long)(position + inputBlockSize) < c90e7c90ead6c95222c8a43ceed60a2b1.Length)
                        {
                            c90e7c90ead6c95222c8a43ceed60a2b1.Read(numArray2, 0, inputBlockSize);
                            int count = decryptor.TransformBlock(numArray2, 0, inputBlockSize, numArray1, 0);
                            c9654c418e330d33bb3f6a61645043740.cc894a1bd974202896bb4271f940b47ba.Write(numArray1, 0, count);
                            position += inputBlockSize;
                        }
label_27:
                        switch (7)
                        {
                        case 0:
                            goto label_27;

                        default:
                            c90e7c90ead6c95222c8a43ceed60a2b1.Read(numArray2, 0, (int)(c90e7c90ead6c95222c8a43ceed60a2b1.Length - (long)position));
                            byte[] numArray3 = decryptor.TransformFinalBlock(numArray2, 0, (int)(c90e7c90ead6c95222c8a43ceed60a2b1.Length - (long)position));
                            c9654c418e330d33bb3f6a61645043740.cc894a1bd974202896bb4271f940b47ba.Write(numArray3, 0, (int)c66a1c83bdee03fa41a70c643b5176698.c572aba370be49804cbdb0b35312bea94(numArray3));
                            stream          = (Stream)c9654c418e330d33bb3f6a61645043740.cc894a1bd974202896bb4271f940b47ba;
                            stream.Position = 0L;
                            memoryStream    = c9654c418e330d33bb3f6a61645043740.cc894a1bd974202896bb4271f940b47ba;
                            break;
                        }
                    }
                }
                if (((int)num1 & 8) != 0)
                {
label_30:
                    switch (3)
                    {
                    case 0:
                        goto label_30;

                    default:
                        if (c9654c418e330d33bb3f6a61645043740.c9eda15cf80fff9318c8c21fbca205f58 == null)
                        {
label_32:
                            switch (7)
                            {
                            case 0:
                                goto label_32;

                            default:
                                if (c9654c418e330d33bb3f6a61645043740.c01552ca16663ec31f968e0ecd31680f2 == int.MinValue)
                                {
label_34:
                                    switch (2)
                                    {
                                    case 0:
                                        goto label_34;

                                    default:
                                        c9654c418e330d33bb3f6a61645043740.c9eda15cf80fff9318c8c21fbca205f58.Capacity = (int)stream.Length * 2;
                                        break;
                                    }
                                }
                                else
                                {
                                    c9654c418e330d33bb3f6a61645043740.c9eda15cf80fff9318c8c21fbca205f58.Capacity = c9654c418e330d33bb3f6a61645043740.c01552ca16663ec31f968e0ecd31680f2;
                                    break;
                                }
                            }
                        }
                        c9654c418e330d33bb3f6a61645043740.c9eda15cf80fff9318c8c21fbca205f58.Position = 0L;
                        DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress);
                        int           num2          = 1000;
                        byte[]        buffer        = cf6c44ce1629f394b5ef11499eb386125.c27c941905305b0ff3e7324bc79625bf4(num2);
                        int           count;
                        do
                        {
                            count = deflateStream.Read(buffer, 0, num2);
                            if (count > 0)
                            {
label_39:
                                switch (4)
                                {
                                case 0:
                                    goto label_39;

                                default:
                                    c9654c418e330d33bb3f6a61645043740.c9eda15cf80fff9318c8c21fbca205f58.Write(buffer, 0, count);
                                    break;
                                }
                            }
                        }while (count >= num2);
label_42:
                        switch (2)
                        {
                        case 0:
                            goto label_42;

                        default:
                            memoryStream = c9654c418e330d33bb3f6a61645043740.c9eda15cf80fff9318c8c21fbca205f58;
                            break;
                        }
                    }
                }
                if (memoryStream != null)
                {
label_45:
                    switch (4)
                    {
                    case 0:
                        goto label_45;

                    default:
                        return(memoryStream.ToArray());
                    }
                }
                else
                {
                    byte[] numArray = cf6c44ce1629f394b5ef11499eb386125.c27c941905305b0ff3e7324bc79625bf4((int)checked ((IntPtr) unchecked (c90e7c90ead6c95222c8a43ceed60a2b1.Length - c90e7c90ead6c95222c8a43ceed60a2b1.Position)));
                    c90e7c90ead6c95222c8a43ceed60a2b1.Read(numArray, 0, (int)c66a1c83bdee03fa41a70c643b5176698.c572aba370be49804cbdb0b35312bea94(numArray));
                    return(numArray);
                }
            }
        }
コード例 #56
0
        public System.Security.Cryptography.ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey, out System.Security.Cryptography.SymmetricAlgorithm algorithm)
        {
            System.Security.Cryptography.DES des;
            switch (this._algorithm)
            {
            case EncryptionAlgorithm.Des:
                des      = new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;
                if (bytesKey != null)
                {
                    des.Key = bytesKey;
                    _encKey = des.Key;
                    break;
                }
                _encKey = des.Key;
                break;

            case EncryptionAlgorithm.Rc2:
                RC2 rc = new RC2CryptoServiceProvider();
                rc.Mode = CipherMode.CBC;
                if (bytesKey != null)
                {
                    rc.Key  = bytesKey;
                    _encKey = rc.Key;
                }
                else
                {
                    _encKey = rc.Key;
                }
                if (_initVec == null)
                {
                    _initVec = rc.IV;
                }
                else
                {
                    rc.IV = _initVec;
                }
                algorithm = rc;
                return(rc.CreateEncryptor());

            case EncryptionAlgorithm.Rijndael:
            {
                Rijndael rijndael = new RijndaelManaged();
                rijndael.Mode = System.Security.Cryptography.CipherMode.CBC;
                if (bytesKey != null)
                {
                    rijndael.Key = bytesKey;
                    _encKey      = rijndael.Key;
                }
                else
                {
                    _encKey = rijndael.Key;
                }
                if (_initVec == null)
                {
                    _initVec = rijndael.IV;
                }
                else
                {
                    rijndael.IV = _initVec;
                }
                algorithm = rijndael;
                return(rijndael.CreateEncryptor());
            }

            case EncryptionAlgorithm.TripleDes:
            {
                TripleDES edes = new TripleDESCryptoServiceProvider();
                edes.Mode = CipherMode.CBC;
                if (bytesKey != null)
                {
                    edes.Key = bytesKey;
                    _encKey  = edes.Key;
                }
                else
                {
                    _encKey = edes.Key;
                }
                if (_initVec == null)
                {
                    _initVec = edes.IV;
                }
                else
                {
                    edes.IV = _initVec;
                }
                algorithm = edes;
                return(edes.CreateEncryptor());
            }

            default:
                throw new CryptographicException("Algorithm '" + _algorithm + "' not supported.");
            }
            if (_initVec == null)
            {
                _initVec = des.IV;
            }
            else
            {
                des.IV = _initVec;
            }
            algorithm = des;
            return(des.CreateEncryptor());
        }
コード例 #57
0
 public static ICryptoTransform CreateWeakEncryptor(this DESCryptoServiceProvider cryptoProvider)
 {
     return(CreateWeakEncryptor(cryptoProvider, cryptoProvider.Key, cryptoProvider.IV));
 }
コード例 #58
0
        byte[] decrypt(byte[] encryptedData)
        {
            var reader      = new BinaryReader(new MemoryStream(encryptedData));
            int headerMagic = reader.ReadInt32();

            if (headerMagic == 0x04034B50)
            {
                throw new NotImplementedException("Not implemented yet since I haven't seen anyone use it.");
            }

            byte encryption = (byte)(headerMagic >> 24);

            if ((headerMagic & 0x00FFFFFF) != 0x007D7A7B)               // Check if "{z}"
            {
                throw new ApplicationException(string.Format("Invalid SA header magic 0x{0:X8}", headerMagic));
            }

            switch (encryption)
            {
            case 1:
                int totalInflatedLength = reader.ReadInt32();
                if (totalInflatedLength < 0)
                {
                    throw new ApplicationException("Invalid length");
                }
                var inflatedBytes = new byte[totalInflatedLength];
                int partInflatedLength;
                for (int inflateOffset = 0; inflateOffset < totalInflatedLength; inflateOffset += partInflatedLength)
                {
                    int partLength = reader.ReadInt32();
                    partInflatedLength = reader.ReadInt32();
                    if (partLength < 0 || partInflatedLength < 0)
                    {
                        throw new ApplicationException("Invalid length");
                    }
                    var inflater = new Inflater(true);
                    inflater.SetInput(encryptedData, checked ((int)reader.BaseStream.Position), partLength);
                    reader.BaseStream.Seek(partLength, SeekOrigin.Current);
                    int realInflatedLen = inflater.Inflate(inflatedBytes, inflateOffset, inflatedBytes.Length - inflateOffset);
                    if (realInflatedLen != partInflatedLength)
                    {
                        throw new ApplicationException("Could not inflate");
                    }
                }
                return(inflatedBytes);

            case 2:
                if (resourceDecrypterInfo.DES_Key == null || resourceDecrypterInfo.DES_IV == null)
                {
                    throw new ApplicationException("DES key / iv have not been set yet");
                }
                using (var provider = new DESCryptoServiceProvider()) {
                    provider.Key = resourceDecrypterInfo.DES_Key;
                    provider.IV  = resourceDecrypterInfo.DES_IV;
                    using (var transform = provider.CreateDecryptor()) {
                        return(decrypt(transform.TransformFinalBlock(encryptedData, 4, encryptedData.Length - 4)));
                    }
                }

            case 3:
                if (resourceDecrypterInfo.AES_Key == null || resourceDecrypterInfo.AES_IV == null)
                {
                    throw new ApplicationException("AES key / iv have not been set yet");
                }
                using (var provider = new RijndaelManaged()) {
                    provider.Key = resourceDecrypterInfo.AES_Key;
                    provider.IV  = resourceDecrypterInfo.AES_IV;
                    using (var transform = provider.CreateDecryptor()) {
                        return(decrypt(transform.TransformFinalBlock(encryptedData, 4, encryptedData.Length - 4)));
                    }
                }

            default:
                throw new ApplicationException(string.Format("Unknown encryption type 0x{0:X2}", encryption));
            }
        }
コード例 #59
0
        /// <summary>
        /// 解密函数
        /// </summary>
        /// <param name="ciphertext"></param>
        /// <param name="argumentParam"></param>
        /// <returns></returns>
        public string Decrypt(string ciphertext, params object[] argumentParam)
        {
            string originalText = null;

            if (!this.IsCiphertext(ciphertext))
            {
                throw new Exception("不是标准的DES密文格式,无法进行解密");
            }

            #region 验证密文

            byte[] cipherBytes = null;
            int    len         = ciphertext.Length / 2;
            cipherBytes = new byte[len];
            int x, i;

            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(ciphertext.Substring(x * 2, 2), 16);
                cipherBytes[x] = (byte)i;
            }

            #endregion

            #region 获取解密算法

            string assignKey;
            object obj_argKey = null != argumentParam && argumentParam.Length > 0 ? argumentParam.First() : null;
            if (null == obj_argKey || string.IsNullOrEmpty(obj_argKey.ToString()))
            {
                assignKey = this.AlgorithmKey;
            }
            else
            {
                assignKey = MD5Handler.Generate(obj_argKey.ToString(), true).Top(8);
            }

            ICryptoTransform transform = null;
            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                desProvider.Key = ASCIIEncoding.ASCII.GetBytes(assignKey);
                desProvider.IV  = ASCIIEncoding.ASCII.GetBytes(assignKey);
                transform       = desProvider.CreateDecryptor();
            }

            #endregion

            #region 执行解密

            using (MemoryStream ms = new MemoryStream())
            {
                CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.FlushFinalBlock();
                originalText = Encoding.Default.GetString(ms.ToArray());
            }

            #endregion

            return(originalText);
        }
コード例 #60
0
        /*
         * DES Algorithm contains both the encryption and decryption.
         * DESAlgorithm ( <string> input file name, <string> output file name, <string> key ,<string> mode=CBC or ECB or CFB , <bool> is the process Encryption? )
         * EX: DESAlgorithm("C:\thienphuoc.png","C:\thienphuoc.png.tpEn","thienphuoc","CBC",true)
         */
        void DESAlgorithm(string sInputFilename, string sOutputFilename, string sKey, string mode, bool isEncrypt)
        {
            byte[] bytes = Convert.FromBase64String(sKey); //Key 8 bytes = 64bits.

            //Open the input file and create the output file.
            FileStream fsInput  = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
            FileStream fsOutput = new FileStream(sOutputFilename, FileMode.OpenOrCreate, FileAccess.Write);

            fsOutput.SetLength(0);

            //Each reading 100bytes.
            byte[] bin    = new byte[100];
            long   rdlen  = 0;
            long   totlen = fsInput.Length;//Total length.
            int    len;

            //Set parameter for progress bar.
            progressBar1.Minimum = 0;
            progressBar1.Maximum = (int)fsInput.Length;

            //DES
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

            //Set mode for DES Algorithm.
            if (mode == "ECB")
            {
                DES.Mode = CipherMode.ECB;
            }
            else if (mode == "CBC")
            {
                DES.Mode = CipherMode.CBC;
            }
            else if (mode == "CFB")
            {
                DES.Mode = CipherMode.CFB;
            }

            //Encrypting
            CryptoStream encStream;

            if (isEncrypt)
            {
                encStream = new CryptoStream(fsOutput, DES.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
            }
            else
            {
                encStream = new CryptoStream(fsOutput, DES.CreateDecryptor(bytes, bytes), CryptoStreamMode.Write);
            }


            //Read from the input file ,each reading 100 bytes,then encrypted and written to the output file.
            while (rdlen < totlen)
            {
                len = fsInput.Read(bin, 0, 100);//Each reading 100bytes
                encStream.Write(bin, 0, len);
                progressBar1.Value = (int)rdlen;
                rdlen = rdlen + len;
                this.progressBar1.PerformStep();
            }


            if (progressBar1.IsHandleCreated && isEncryptFile)
            {
                System.Diagnostics.Process prc = new System.Diagnostics.Process();
                prc.StartInfo.FileName = Path.GetDirectoryName(outputFileName);
                prc.Start();
                //MessageBox.Show("Mã hóa thành công!");
            }

            // Close all files.
            encStream.Close();
            fsOutput.Close();
            fsInput.Close();
        }