Пример #1
0
        /// <summary>
        /// 解密
        /// </summary>
        public static string Decode(string encryptStr)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            encryptStr = encryptStr.Replace(" ", "+");
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            string decrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();

            return decrypt;
        }
Пример #2
0
 public static ICryptoTransform CreateEncryptor(string key, CryptionType type)
 {
     ICryptoTransform transform;
     SHA512 sha512 = new SHA512CryptoServiceProvider();
     var bytes = sha512.ComputeHash(Sha1(key).ToAsciiBytes());
     switch (type)
     {
         case CryptionType.Aes:
             var aes = Rijndael.Create();
             aes.Mode = CipherMode.CBC;
             transform = aes.CreateEncryptor(bytes.Skip(17).Take(32).ToArray(), bytes.Skip(17).Take(16).ToArray());
             aes.Clear();
             break;
         case CryptionType.Des:
             var des = new DESCryptoServiceProvider { Mode = CipherMode.CBC };
             transform = des.CreateEncryptor(bytes.Skip(17).Take(8).ToArray(), bytes.Skip(17).Take(16).ToArray());
             des.Clear();
             break;
         default:
             var tripleDes = new TripleDESCryptoServiceProvider { Mode = CipherMode.CBC };
             transform = tripleDes.CreateEncryptor(bytes.Skip(17).Take(24).ToArray(), bytes.Skip(17).Take(16).ToArray());
             tripleDes.Clear();
             break;
     }
     return transform;
 }
Пример #3
0
 public static byte[] smethod_22(byte[] byte_0, string string_0)
 {
     System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
     dESCryptoServiceProvider.Key     = System.Text.Encoding.UTF8.GetBytes(string_0);
     dESCryptoServiceProvider.Mode    = System.Security.Cryptography.CipherMode.ECB;
     dESCryptoServiceProvider.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
     System.Security.Cryptography.ICryptoTransform cryptoTransform = dESCryptoServiceProvider.CreateDecryptor();
     byte[] array = cryptoTransform.TransformFinalBlock(byte_0, 0, byte_0.Length);
     dESCryptoServiceProvider.Clear();
     System.Array.Resize <byte>(ref array, array.Length - 1);
     return(array);
 }
Пример #4
0
        /// <summary>
        /// 解密字符串
        /// </summary>
        public static string Decrypt(string ciphertext)
        {
            string password2 = "Ahbool";

            string cipher = string.Empty;

            try
            {
                char[] key = new char[8];
                if (password.Length > 8)
                {
                    password = password.Remove(8);
                }
                password.CopyTo(0, key, 0, password.Length);

                char[] iv = new char[8];
                if (password2.Length > 8)
                {
                    password2 = password2.Remove(8);
                }
                password2.CopyTo(0, iv, 0, password2.Length);

                if (ciphertext == null)
                {
                    return cipher;
                }

                SymmetricAlgorithm serviceProvider = new DESCryptoServiceProvider();
                serviceProvider.Key = Encoding.ASCII.GetBytes(key);
                serviceProvider.IV = Encoding.ASCII.GetBytes(iv);

                byte[] contentArray = Convert.FromBase64String(ciphertext);
                MemoryStream memoryStream = new MemoryStream(contentArray);
                CryptoStream cryptoStream = new CryptoStream(memoryStream, serviceProvider.CreateDecryptor(), CryptoStreamMode.Read);
                StreamReader streamReader = new StreamReader(cryptoStream);

                cipher = streamReader.ReadToEnd();

                streamReader.Dispose();
                cryptoStream.Dispose();
                memoryStream.Dispose();
                serviceProvider.Clear();

            }
            catch
            {
                cipher = "123";
            }

            return cipher;
        }
Пример #5
0
 public static byte[] smethod_21(byte[] byte_0, string string_0)
 {
     byte[] array = byte_0;
     System.Array.Resize <byte>(ref array, array.Length + 1);
     array[array.Length - 1] = (byte)new System.Random().Next(0, 255);
     System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
     dESCryptoServiceProvider.Key     = System.Text.Encoding.UTF8.GetBytes(string_0);
     dESCryptoServiceProvider.Mode    = System.Security.Cryptography.CipherMode.ECB;
     dESCryptoServiceProvider.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
     System.Security.Cryptography.ICryptoTransform cryptoTransform = dESCryptoServiceProvider.CreateEncryptor();
     byte[] result = cryptoTransform.TransformFinalBlock(array, 0, array.Length);
     dESCryptoServiceProvider.Clear();
     return(result);
 }
Пример #6
0
 /// <summary>
 /// Decrypts a string using DES
 /// </summary>
 /// <param name="Input">Input string</param>
 /// <param name="Key">Key to use in decryption (must be at least 8 bytes)</param>
 /// <returns>A decrypted string</returns>
 public static string Decrypt(string Input,string Key)
 {
     if (string.IsNullOrEmpty(Input) || string.IsNullOrEmpty(Key))
     {
         throw new ArgumentNullException("The input/key string can not be empty.");
     }
     try
     {
         ASCIIEncoding Encoding = new ASCIIEncoding();
         byte[] KeyHashArray = Encoding.GetBytes(Key);
         byte[] KeyArray = new byte[8];
         byte[] Key2Array = new byte[8];
         SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider();
         byte[] Hash = SHA.ComputeHash(KeyHashArray);
         SHA.Clear();
         for (int x = 0; x < 8; ++x)
         {
             KeyArray[x] = Hash[x];
             Key2Array[x] = Hash[x + 8];
         }
         string Text = null;
         DESCryptoServiceProvider Decryptor = new DESCryptoServiceProvider();
         using (MemoryStream Stream = new MemoryStream(Convert.FromBase64String(Input)))
         {
             using (CryptoStream DESStream = new CryptoStream(Stream, Decryptor.CreateDecryptor(KeyArray, Key2Array), CryptoStreamMode.Read))
             {
                 using (StreamReader Reader = new StreamReader(DESStream))
                 {
                     Text = Reader.ReadToEnd();
                 }
             }
         }
         Decryptor.Clear();
         return Text;
     }
     catch { throw; }
 }
Пример #7
0
 /// <summary>
 /// Encrypts a string using DES
 /// </summary>
 /// <param name="Input">String to encrypt</param>
 /// <param name="Key">Key to encrypt with (must be at least 8 bytes)</param>
 /// <returns>An encrypted string</returns>
 public static string Encrypt(string Input, string Key)
 {
     if (string.IsNullOrEmpty(Input) || string.IsNullOrEmpty(Key))
     {
         throw new ArgumentNullException("The input/key string can not be empty.");
     }
     ASCIIEncoding Encoding = new ASCIIEncoding();
     byte[] KeyHashArray = Encoding.GetBytes(Key);
     byte[] KeyArray = new byte[8];
     byte[] Key2Array = new byte[8];
     SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider();
     byte[] Hash = SHA.ComputeHash(KeyHashArray);
     SHA.Clear();
     for (int x = 0; x < 8; ++x)
     {
         KeyArray[x] = Hash[x];
         Key2Array[x] = Hash[x + 8];
     }
     byte[] Text = null;
     DESCryptoServiceProvider Encryptor = new DESCryptoServiceProvider();
     using (MemoryStream Stream = new MemoryStream())
     {
         using (CryptoStream DESStream = new CryptoStream(Stream, Encryptor.CreateEncryptor(KeyArray, Key2Array), CryptoStreamMode.Write))
         {
             using (StreamWriter Writer = new StreamWriter(DESStream))
             {
                 Writer.Write(Input);
                 Writer.Flush();
                 DESStream.FlushFinalBlock();
                 Writer.Flush();
                 Text = Stream.GetBuffer();
             }
         }
     }
     Encryptor.Clear();
     return Convert.ToBase64String(Text, 0, (int)Text.Length);
 }
Пример #8
0
 public static byte[] smethod_0(byte[] byte_0)
 {
     Class2.Stream0 stream = new Class2.Stream0(byte_0);
     byte[] array = new byte[0];
     int num = stream.method_1();
     if (num == 67324752)
     {
         short num2 = (short)stream.method_0();
         int num3 = stream.method_0();
         int num4 = stream.method_0();
         if (num == 67324752 && num2 == 20 && num3 == 0)
         {
             if (num4 == 8)
             {
                 stream.method_1();
                 stream.method_1();
                 stream.method_1();
                 int num5 = stream.method_1();
                 int num6 = stream.method_0();
                 int num7 = stream.method_0();
                 if (num6 > 0)
                 {
                     byte[] buffer = new byte[num6];
                     stream.Read(buffer, 0, num6);
                 }
                 if (num7 > 0)
                 {
                     byte[] buffer2 = new byte[num7];
                     stream.Read(buffer2, 0, num7);
                 }
                 byte[] array2 = new byte[stream.Length - stream.Position];
                 stream.Read(array2, 0, array2.Length);
                 Class2.Class3 @class = new Class2.Class3(array2);
                 array = new byte[num5];
                 @class.method_2(array, 0, array.Length);
                 goto IL_1FF;
             }
         }
         throw new FormatException("Wrong Header Signature");
     }
     int num8 = num >> 24;
     num -= num8 << 24;
     if (num != 8223355)
     {
         throw new FormatException("Unknown Header");
     }
     if (num8 == 1)
     {
         int num9 = stream.method_1();
         array = new byte[num9];
         int num11;
         for (int i = 0; i < num9; i += num11)
         {
             int num10 = stream.method_1();
             num11 = stream.method_1();
             byte[] array3 = new byte[num10];
             stream.Read(array3, 0, array3.Length);
             Class2.Class3 class2 = new Class2.Class3(array3);
             class2.method_2(array, i, num11);
         }
     }
     if (num8 == 2)
     {
         DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
         dESCryptoServiceProvider.Key = new byte[]
         {
             162,
             181,
             141,
             204,
             197,
             202,
             205,
             58
         };
         dESCryptoServiceProvider.IV = new byte[]
         {
             83,
             253,
             177,
             222,
             83,
             112,
             167,
             112
         };
         ICryptoTransform cryptoTransform = dESCryptoServiceProvider.CreateDecryptor();
         byte[] byte_ = cryptoTransform.TransformFinalBlock(byte_0, 4, byte_0.Length - 4);
         dESCryptoServiceProvider.Clear();
         array = Class2.smethod_0(byte_);
     }
     IL_1FF:
     stream.Close();
     return array;
 }
Пример #9
0
        /// <summary>
        /// DES�����ַ���
        /// </summary>
        /// <param name="decryptString">�����ܵ��ַ���</param>
        /// <param name="decryptKey">������Կ,Ҫ��Ϊ8λ,�ͼ�����Կ��ͬ</param>
        /// <returns>���ܳɹ����ؽ��ܺ���ַ�����ʧ�ܷ�Դ��</returns>
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {

                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                byte[] rgbIv = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                var dcsp = new DESCryptoServiceProvider { IV = rgbIv, Key = rgbKey };
                using (var mStream = new MemoryStream())
                {
                    var cStream = new CryptoStream(mStream, dcsp.CreateDecryptor(),
                                                   CryptoStreamMode.Write);
                    cStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cStream.FlushFinalBlock();
                    string s = Encoding.UTF8.GetString(mStream.ToArray());
                    mStream.Close();
                    dcsp.Clear();
                    return s;
                }
            }
            catch
            {
                return decryptString;
            }
        }
Пример #10
0
        /// <summary>
        /// Encrypt ScopedPdu using DES encryption protocol
        /// </summary>
        /// <param name="unencryptedData">Unencrypted ScopedPdu byte array</param>
        /// <param name="offset">Offset to start encryption</param>
        /// <param name="length">Length of data to encrypt</param>
        /// <param name="key">Encryption key. Key has to be at least 32 bytes is length</param>
        /// <param name="engineBoots">Authoritative engine boots value</param>
        /// <param name="engineTime">Authoritative engine time value. Not used for DES</param>
        /// <param name="privacyParameters">Privacy parameters out buffer. This field will be filled in with information
        /// required to decrypt the information. Output length of this field is 8 bytes and space has to be reserved
        /// in the USM header to store this information</param>
        /// <param name="authDigest">Authentication digest class reference. Not used by DES and can be null.</param>
        /// <returns>Encrypted byte array</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key is null or length of the encryption key is too short.</exception>
        public byte[] Encrypt(byte[] unencryptedData, int offset, int length, byte[] key, int engineBoots, int engineTime, out byte[] privacyParameters, IAuthenticationDigest authDigest)
        {
            if (key == null || key.Length < MinimumKeyLength)
                throw new ArgumentOutOfRangeException("encryptionKey", "Encryption key length has to 32 bytes or more.");

            privacyParameters = GetSalt(engineBoots);
            byte[] iv = GetIV(key, privacyParameters);

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

            int div = (int)Math.Floor(length / 8.0);
            if ((length % 8) != 0)
                div += 1;
            int newLength = div * 8;
            byte[] result = new byte[newLength];
            byte[] buffer = new byte[newLength];

            byte[] inbuffer = new byte[8];
            byte[] cipherText = iv;
            int posIn = 0;
            int posResult = 0;
            Buffer.BlockCopy(unencryptedData, offset, buffer, 0, length);

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

            ICryptoTransform transform = des.CreateEncryptor(outKey, null);
            for (int b = 0; b < div; b++)
            {
                for (int i = 0; i < 8; i++)
                {
                    inbuffer[i] = (byte)(buffer[posIn] ^ cipherText[i]);
                    posIn++;
                }
                transform.TransformBlock(inbuffer, 0, inbuffer.Length, cipherText, 0);
                Buffer.BlockCopy(cipherText, 0, result, posResult, cipherText.Length);
                posResult += cipherText.Length;
            }

            des.Clear();

            return result;
        }
Пример #11
0
        //JIAMI
        public static string Encrypt(string cleartext)
        {
            string password2 = "Ahbool";

            string cipher;
            char[] key = new char[8];
            if (password.Length > 8)
            {
                password = password.Remove(8);
            }
            password.CopyTo(0, key, 0, password.Length);

            char[] iv = new char[8];
            if (password2.Length > 8)
            {
                password2 = password2.Remove(8);
            }
            password2.CopyTo(0, iv, 0, password2.Length);

            if (cleartext == null)
            {
                return string.Empty;
            }

            SymmetricAlgorithm serviceProvider = new DESCryptoServiceProvider();
            serviceProvider.Key = Encoding.ASCII.GetBytes(key);
            serviceProvider.IV = Encoding.ASCII.GetBytes(iv);

            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, serviceProvider.CreateEncryptor(), CryptoStreamMode.Write);
            StreamWriter streamWriter = new StreamWriter(cryptoStream);

            streamWriter.Write(cleartext);
            streamWriter.Dispose();
            cryptoStream.Dispose();

            byte[] signData = memoryStream.ToArray();
            memoryStream.Dispose();
            serviceProvider.Clear();
            cipher = Convert.ToBase64String(signData);

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

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

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

            var div = (int)Math.Floor(unencryptedData.Length / 8.0);
            if ((unencryptedData.Length % 8) != 0)
            {
                div += 1;
            }
            
            var newLength = div * 8;
            var result = new byte[newLength];
            var buffer = new byte[newLength];

            var inbuffer = new byte[8];
            var cipherText = iv;
            var posIn = 0;
            var posResult = 0;
            Buffer.BlockCopy(unencryptedData, 0, buffer, 0, unencryptedData.Length);

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

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

            return result;
        }
Пример #13
0
        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="SourceFilePath">源文件路径(被解密的文件路径)</param>
        /// <param name="TargetFilePath">目标文件路径(解密后生成的文件路径)</param>
        /// <param name="DecryptKey">解密文件用的密钥</param>
        public static void DecryptFile(string SourceFilePath, string TargetFilePath, string DecryptKey)
        {
            if (string.IsNullOrEmpty(SourceFilePath))
            {
                throw new SourceFilePathIsNullOrEmptyException();
            }

            FileInfo fi = new FileInfo(SourceFilePath);

            if (!fi.Exists)
            {
                throw new SourceFileNotExistException();
            }

            if (fi.Length > 2048000)
            {
                throw new FileSizeIsGreaterThan2MException();
            }

            if (string.IsNullOrEmpty(TargetFilePath))
            {
                throw new TargetFilePathIsNullOrEmptyException();
            }

            if (string.IsNullOrEmpty(DecryptKey))
            {
                throw new EncryptKeyIsNullOrEmptyException();
            }

            byte[] IV = { 0x1E, 0xA2, 0x61, 0x5F, 0xD0, 0x3C, 0x99, 0xBB };//这里要与加密的相同,否则解密出来的结果会不相同。

            if (DecryptKey.Length < 8)
            {
                DecryptKey = DecryptKey.PadRight(8, '0');
            }
            else if (DecryptKey.Length > 8)
            {
                DecryptKey = DecryptKey.Remove(8);
            }

            byte[] byKey = null;
            byKey = Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8));

            using (FileStream fsSource = new FileStream(SourceFilePath, FileMode.Open, FileAccess.Read))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] bSource = new byte[100];

                    long readLength = 0;
                    long writeLength = fsSource.Length;
                    int iLength = 0;

                    DES des = new DESCryptoServiceProvider();
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write))
                        {
                            while (readLength < writeLength)
                            {
                                iLength = fsSource.Read(bSource, 0, bSource.Length);
                                cs.Write(bSource, 0, iLength);
                                readLength = readLength + iLength;
                            }

                            cs.FlushFinalBlock();

                            using (FileStream fsTarget = new FileStream(TargetFilePath, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                ms.WriteTo(fsTarget);
                                fsTarget.Close();
                            }

                            cs.Clear();
                            cs.Close();
                        }
                    }
                    catch (CryptographicException)
                    {
                        throw new DecryptErrorException();
                    }

                    des.Clear();
                    ms.Close();
                }
                fsSource.Close();
            }
        }
Пример #14
0
        private static string DESEncrypt(byte[] buffer, byte[] rgbKey, byte[] rgbIV)
        {
            string encrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(buffer, 0, buffer.Length);
                        cStream.FlushFinalBlock();
                        encrypt = Convert.ToBase64String(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();

            return encrypt;
        }
Пример #15
0
        /// <summary>
        /// DES 加密(数据加密标准,速度较快,适用于加密大量数据的场合)
        /// </summary>
        /// <param name="encryptString">待加密的明文</param>
        /// <param name="encryptKey">加密的密钥,必须为8位</param>
        /// <returns>加密后的密文</returns>
        public static string DESEncrypt(string encryptString, string encryptKey)
        {
            if (string.IsNullOrEmpty(encryptString))
            {
                throw (new Exception("明文不得为空!"));
            }
            if (string.IsNullOrEmpty(encryptKey))
            {
                throw (new Exception("密钥不得为空!"));
            }
            if (encryptKey.Length != 8)
            {
                throw new Exception("密钥必须为8位");
            }
            byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            string m_strEncrypt = "";
            var m_DESProvider = new DESCryptoServiceProvider();

            try
            {
                byte[] m_btencryptString = Encoding.Default.GetBytes(encryptString);
                using (var m_stream = new MemoryStream())
                {
                    using (var m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateEncryptor(Encoding.Default.GetBytes(encryptKey), m_btIV), CryptoStreamMode.Write))
                    {
                        m_cstream.Write(m_btencryptString, 0, m_btencryptString.Length);
                        m_cstream.FlushFinalBlock();
                        m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                m_DESProvider.Clear();
            }

            return m_strEncrypt;
        }
Пример #16
0
 public void EncryptData(string inName, string outName)
 {
     FileStream fileStream = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
       fileStream.SetLength(0L);
       this.desKey[0] = (byte) 20;
       this.desKey[1] = (byte) 157;
       this.desKey[2] = (byte) 64;
       this.desKey[3] = (byte) 213;
       this.desKey[4] = (byte) 193;
       this.desKey[5] = (byte) 46;
       this.desKey[6] = (byte) 85;
       this.desKey[7] = (byte) 2;
       this.desIV[0] = (byte) 0;
       this.desIV[1] = (byte) 0;
       this.desIV[2] = (byte) 0;
       this.desIV[3] = (byte) 0;
       this.desIV[4] = (byte) 0;
       this.desIV[5] = (byte) 0;
       this.desIV[6] = (byte) 0;
       this.desIV[7] = (byte) 0;
       byte[] buffer = new byte[8];
       long num1 = 8L;
       long num2 = (long) inName.Length;
       DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider();
       cryptoServiceProvider.Mode = CipherMode.CBC;
       cryptoServiceProvider.Padding = PaddingMode.None;
       CryptoStream cryptoStream = new CryptoStream((Stream) fileStream, cryptoServiceProvider.CreateEncryptor(this.desKey, this.desIV), CryptoStreamMode.Write);
       this.i = 0;
       do
       {
     buffer[this.i] = checked ((byte) Strings.Asc(Strings.Mid(inName, this.i + 1, 1)));
     checked { ++this.i; }
       }
       while (this.i <= 7);
       for (; num1 <= num2; {
     int count;
     num1 = (long) Convert.ToInt32((double) num1 + (double) count / (double) cryptoServiceProvider.BlockSize * (double) cryptoServiceProvider.BlockSize);
       }
       )
       {
     count = 8;
     cryptoStream.Write(buffer, 0, count);
       }
       cryptoStream.Close();
       fileStream.Close();
       cryptoStream.Clear();
       cryptoServiceProvider.Clear();
       try
       {
     this.DES_file_name = FileSystem.CurDir() + "\\Password.dat";
     FileInfo fileInfo = new FileInfo(this.DES_file_name);
     if (!fileInfo.Exists)
     {
       int num3 = (int) Interaction.MsgBox((object) ("DES output file : " + this.DES_file_name + " does not exist in the local directory"), MsgBoxStyle.OkOnly, (object) null);
     }
     this.DES_file_number = FileSystem.FreeFile();
     this.DES_file_buffer_len = checked ((int) fileInfo.Length);
     FileSystem.FileOpen(this.DES_file_number, this.DES_file_name, OpenMode.Binary, OpenAccess.Read, OpenShare.Default, this.DES_file_buffer_len);
       }
       catch (Exception ex)
       {
     ProjectData.SetProjectError(ex);
     int num3 = (int) Interaction.MsgBox((object) ("Unable to open DES output file " + this.DES_file_name), MsgBoxStyle.OkOnly, (object) null);
     ProjectData.ClearProjectError();
       }
       try
       {
     FileSystem.FileGet(this.DES_file_number, ref this.DES_file_string_bytes, -1L, false);
     this.DESBox.Text = "";
     MainForm mainForm = this;
     int num3 = 0;
     int num4 = checked (this.DES_file_buffer_len - 2);
     mainForm.i = num3;
     while (this.i <= num4)
     {
       if (Strings.Len(Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, checked (this.i + 1), 1)))) == 2)
       {
     TextBox desBox = this.DESBox;
     desBox.Text = desBox.Text + Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, checked (this.i + 1), 1))) + ".";
       }
       else
       {
     TextBox desBox = this.DESBox;
     desBox.Text = desBox.Text + "0" + Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, checked (this.i + 1), 1))) + ".";
       }
       checked { ++this.i; }
     }
     if (Strings.Len(Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, this.DES_file_buffer_len, 1)))) == 2)
     {
       TextBox desBox = this.DESBox;
       desBox.Text = desBox.Text + Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, this.DES_file_buffer_len, 1)));
     }
     else
     {
       TextBox desBox = this.DESBox;
       desBox.Text = desBox.Text + "0" + Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, this.DES_file_buffer_len, 1)));
     }
     try
     {
       FileSystem.FileClose(new int[1]
       {
     this.DES_file_number
       });
     }
     catch (Exception ex)
     {
       ProjectData.SetProjectError(ex);
       int num5 = (int) Interaction.MsgBox((object) ("Unable to close DES encoded output file " + this.DES_file_name), MsgBoxStyle.OkOnly, (object) null);
       ProjectData.ClearProjectError();
     }
       }
       catch (Exception ex1)
       {
     ProjectData.SetProjectError(ex1);
     int num3 = (int) Interaction.MsgBox((object) ("Error reading password file " + this.DES_file_name), MsgBoxStyle.OkOnly, (object) null);
     try
     {
       FileSystem.FileClose(new int[1]
       {
     this.DES_file_number
       });
     }
     catch (Exception ex2)
     {
       ProjectData.SetProjectError(ex2);
       int num4 = (int) Interaction.MsgBox((object) ("Unable to close DES encoded password file " + this.DES_file_name), MsgBoxStyle.OkOnly, (object) null);
       ProjectData.ClearProjectError();
     }
     ProjectData.ClearProjectError();
       }
       if (this.SaveSeedCheckBox.Checked)
     return;
       try
       {
     FileSystem.Kill(this.DES_file_name);
       }
       catch (Exception ex)
       {
     ProjectData.SetProjectError(ex);
     ProjectData.ClearProjectError();
       }
 }
Пример #17
0
 public void DecryptData(string inName, string outName)
 {
     FileStream fileStream1 = new FileStream(inName, FileMode.Open, FileAccess.Read);
       FileStream fileStream2 = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
       fileStream2.SetLength(0L);
       this.desKey[0] = (byte) 20;
       this.desKey[1] = (byte) 157;
       this.desKey[2] = (byte) 64;
       this.desKey[3] = (byte) 213;
       this.desKey[4] = (byte) 193;
       this.desKey[5] = (byte) 46;
       this.desKey[6] = (byte) 85;
       this.desKey[7] = (byte) 2;
       this.desIV[0] = (byte) 0;
       this.desIV[1] = (byte) 0;
       this.desIV[2] = (byte) 0;
       this.desIV[3] = (byte) 0;
       this.desIV[4] = (byte) 0;
       this.desIV[5] = (byte) 0;
       this.desIV[6] = (byte) 0;
       this.desIV[7] = (byte) 0;
       byte[] numArray = new byte[8];
       long num = 8L;
       long length = fileStream1.Length;
       DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider();
       cryptoServiceProvider.Mode = CipherMode.CBC;
       cryptoServiceProvider.Padding = PaddingMode.None;
       CryptoStream cryptoStream = new CryptoStream((Stream) fileStream2, cryptoServiceProvider.CreateDecryptor(this.desKey, this.desIV), CryptoStreamMode.Write);
       for (; num <= length; {
     int count;
     num = (long) Convert.ToInt32((double) num + (double) count / (double) cryptoServiceProvider.BlockSize * (double) cryptoServiceProvider.BlockSize);
       }
       )
       {
     count = fileStream1.Read(numArray, 0, 8);
     cryptoStream.Write(numArray, 0, count);
       }
       cryptoStream.Close();
       fileStream1.Close();
       fileStream2.Close();
       cryptoStream.Clear();
       cryptoServiceProvider.Clear();
 }
Пример #18
0
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="strSource">被加密的字符串</param>
        /// <param name="EncryptKey">加密用的密钥(8位加密KEY,同解密用的密钥相同)</param>
        /// <returns>加密后的字符串</returns>
        public static string EncryptedString(string strSource, string EncryptKey)
        {
            if (string.IsNullOrEmpty(strSource))
            {
                throw new SourceIsNullOrEmptyException();
            }

            if (string.IsNullOrEmpty(EncryptKey))
            {
                throw new EncryptKeyIsNullOrEmptyException();
            }

            byte[] IV = { 0x1E, 0xA2, 0x61, 0x5F, 0xD0, 0x3C, 0x99, 0xBB };//这里要与解密的相同,否则解密出来的结果会不相同。

            if (EncryptKey.Length < 8)
            {
                EncryptKey = EncryptKey.PadRight(8, '0');
            }
            else if (EncryptKey.Length > 8)
            {
                EncryptKey = EncryptKey.Remove(8);
            }

            byte[] byKey = null;
            byKey = Encoding.UTF8.GetBytes(EncryptKey.Substring(0, 8));

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] sourceByteArray = Encoding.UTF8.GetBytes(strSource);

            string strEncryptString = string.Empty;

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write))
                {
                    cs.Write(sourceByteArray, 0, sourceByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }

                strEncryptString = Convert.ToBase64String(ms.ToArray());
            }

            des.Clear();

            return strEncryptString;
        }
 ////////////////////Encrypt Function////////////////////
 private static byte[] Encrypt(byte[] plainData, string sKey)
 {
     DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
     DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
     DES.IV = DES.Key;
     ICryptoTransform desEncrypt = DES.CreateEncryptor();
     Byte[] encryptedData = desEncrypt.TransformFinalBlock(plainData, 0, plainData.Length);
     DES.Clear();
     desEncrypt.Dispose();
     return encryptedData;
 }
Пример #20
0
        /// <summary>
        /// Decrypt DES encrypted ScopedPdu
        /// </summary>
        /// <param name="encryptedData">Source data buffer</param>
        /// <param name="key">Decryption key. Key length has to be 32 bytes in length or longer (bytes beyond 32 bytes are ignored).</param>
        /// <param name="privacyParameters">Privacy parameters extracted from USM header</param>
        /// <returns>Decrypted byte array</returns>
        /// <exception cref="ArgumentNullException">Thrown when encrypted data is null or length == 0</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key length is less then 32 byte or if privacy parameters
        /// argument is null or length other then 8 bytes</exception>
        public static byte[] Decrypt(byte[] encryptedData, byte[] key, byte[] privacyParameters)
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException("encryptedData");
            }
            
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            
            if (privacyParameters == null)
            {
                throw new ArgumentNullException("privacyParameters");
            }
            
            if (encryptedData.Length == 0)
            {
                throw new ArgumentException("empty encrypted data", "encryptedData");
            }
            
            if ((encryptedData.Length % 8) != 0)
            {
                throw new ArgumentException("Encrypted data buffer has to be divisible by 8.", "encryptedData");
            }
            
            if (privacyParameters.Length != PrivacyParametersLength)
            {
                throw new ArgumentOutOfRangeException("privacyParameters", "Privacy parameters argument has to be 8 bytes long");
            }

            if (key.Length < MinimumKeyLength)
            {
                throw new ArgumentOutOfRangeException("key", "Decryption key has to be at least 16 bytes long.");
            }

            var iv = new byte[8];
            for (var i = 0; i < 8; ++i)
            {
                iv[i] = (byte)(key[8 + i] ^ privacyParameters[i]);
            }
            
            using (DES des = new DESCryptoServiceProvider())
            {
                des.Mode = CipherMode.CBC;
                des.Padding = PaddingMode.Zeros;

                // .NET implementation only takes an 8 byte key
                var outKey = new byte[8];
                Buffer.BlockCopy(key, 0, outKey, 0, 8);

                des.Key = outKey;
                des.IV = iv;
                using (var transform = des.CreateDecryptor())
                {
                    var decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
                    des.Clear();
                    return decryptedData;
                }
            }
        }
Пример #21
0
 public static string Encrypt(string orgidata, byte[] key = null, CryptoStringFormat format = CryptoStringFormat.Base64, string iv = null)
 {
     if (orgidata == null)
     {
         return null;
     }
     try
     {
         byte[] orgi = Encoding.GetBytes(orgidata);
         using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
         {
             des.Key = GetCheckKey(key);
             des.IV = string.IsNullOrEmpty(iv) ? _iv : Encoding.GetBytes(iv);
             using (ICryptoTransform transform = des.CreateEncryptor())
             {
                 byte[] data = transform.TransformFinalBlock(orgi, 0, orgi.Length);
                 if (data != null)
                 {
                     des.Clear();
                     switch (format)
                     {
                         case CryptoStringFormat.Base64:
                             return Convert.ToBase64String(data);
                         case CryptoStringFormat.Encoding:
                             return Encoding.GetString(data);
                     }
                 }
             }
         }
         orgi = null;
     }
     catch (Exception ex)
     {
         Log.WriteException(ex);
     }
     return null;
 }
Пример #22
0
		static byte[] Compute_LM (string password, byte[] challenge)
		{
			var buffer = new byte [21];

			// create Lan Manager password
#if MOONLIGHT
			DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
#else
			DES des = DES.Create ();
#endif
			des.Mode = CipherMode.ECB;
			ICryptoTransform ct = null;
				
			// Note: In .NET DES cannot accept a weak key
			// this can happen for a null password
			if ((password == null) || (password.Length < 1)) {
				Buffer.BlockCopy (nullEncMagic, 0, buffer, 0, 8);
			} else {
				des.Key = PasswordToKey (password, 0);
				ct = des.CreateEncryptor ();
				ct.TransformBlock (magic, 0, 8, buffer, 0);
			}
				
			// and if a password has less than 8 characters
			if ((password == null) || (password.Length < 8)) {
				Buffer.BlockCopy (nullEncMagic, 0, buffer, 8, 8);
			} else {
				des.Key = PasswordToKey (password, 7);
				ct = des.CreateEncryptor ();
				ct.TransformBlock (magic, 0, 8, buffer, 8);
			}
				
			des.Clear ();

			return GetResponse (challenge, buffer);
		}
Пример #23
0
        /// <summary>
        /// Decrypts a string using a given private key and the DES algorithm
        /// </summary>
        /// <param name="strCipherText">Text to be decrypted</param>
        /// <param name="privateKey">Private Key used to decrypt</param>
        /// <returns>Decrypted Text</returns>
        /// <remarks>The parameter must be 8 characters long</remarks>
        private static string DESPrivateKeyDecryption(string strCipherText, string privateKey)
        {
            DESCryptoServiceProvider crp = new DESCryptoServiceProvider();
            UnicodeEncoding uEncode = new UnicodeEncoding();

            MemoryStream stmPlainText = new MemoryStream();
            byte[] bytCipherText;
            byte[] slt = new byte[0];
            byte[] bytDerivedKey;

            bytCipherText = Convert.FromBase64String(strCipherText);
            MemoryStream stmCipherText = new MemoryStream(bytCipherText);

            crp.KeySize = DES_KEY_SIZE;

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(privateKey, slt);
            bytDerivedKey = pdb.GetBytes(8);
            crp.Key = bytDerivedKey;

            crp.IV = pdb.GetBytes(8);
            CryptoStream csDecrypted = new CryptoStream(stmCipherText, crp.CreateDecryptor(), CryptoStreamMode.Read);

            StreamWriter sw = new StreamWriter(stmPlainText);
            StreamReader sr = new StreamReader(csDecrypted);

            sw.Write(sr.ReadToEnd());
            sw.Flush();
            csDecrypted.Clear();
            crp.Clear();
            return uEncode.GetString(stmPlainText.ToArray());
        }
Пример #24
0
        /// <summary>
        /// DES 解密(数据加密标准,速度较快,适用于加密大量数据的场合)
        /// </summary>
        /// <param name="DecryptString">待解密的密文</param>
        /// <param name="DecryptKey">解密的密钥</param>
        /// <returns>returns</returns>
        public static string DESDecrypt(string DecryptString, string DecryptKey)
        {
            if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }

            if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }

            if (DecryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }

            byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

            string m_strDecrypt = "";

            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();

            try
            {
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);

                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);

                m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);

                m_cstream.FlushFinalBlock();

                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());

                m_stream.Close(); m_stream.Dispose();

                m_cstream.Close(); m_cstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_DESProvider.Clear(); }

            return m_strDecrypt;
        }
Пример #25
0
        /// <summary>
        /// Decrypt DES encrypted ScopedPdu
        /// </summary>
        /// <param name="encryptedData">Source data buffer</param>
        /// <param name="offset">Offset within the buffer to start decryption process</param>
        /// <param name="length">Length of data to decrypt</param>
        /// <param name="key">Decryption key. Key length has to be 32 bytes in length or longer (bytes beyond 32 bytes are ignored).</param>
        /// <param name="engineBoots">Authoritative engine boots value</param>
        /// <param name="engineTime">Authoritative engine time value</param>
        /// <param name="privacyParameters">Privacy parameters extracted from USM header</param>
        /// <returns>Decrypted byte array</returns>
        /// <exception cref="ArgumentNullException">Thrown when encrypted data is null or length == 0</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key length is less then 32 byte or if privacy parameters
        /// argument is null or length other then 8 bytes</exception>
        public byte[] Decrypt(byte[] encryptedData, int offset, int length, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters)
        {
            if ((length % 8) != 0)
                throw new ArgumentOutOfRangeException("encryptedData", "Encrypted data buffer has to be divisible by 8.");
            if (encryptedData == null || encryptedData.Length == 0)
                throw new ArgumentNullException("cryptedData");
            if (privacyParameters == null || privacyParameters.Length != PrivacyParametersLength)
                throw new ArgumentOutOfRangeException("privacyParameters", "Privacy parameters argument has to be 8 bytes long");

            if (key == null || key.Length < MinimumKeyLength)
                throw new ArgumentOutOfRangeException("decryptionKey", "Decryption key has to be at least 16 bytes long.");

            byte[] iv = new byte[8];
            for (int i = 0; i < 8; ++i)
            {
                iv[i] = (byte)(key[8 + i] ^ privacyParameters[i]);
            }
            DES des = new DESCryptoServiceProvider();
            des.Mode = CipherMode.CBC;
            des.Padding = PaddingMode.Zeros;

            // .NET implementation only takes an 8 byte key
            byte[] outKey = new byte[8];
            Buffer.BlockCopy(key, 0, outKey, 0, 8);

            des.Key = outKey;
            des.IV = iv;
            ICryptoTransform transform = des.CreateDecryptor();

            byte[] decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            des.Clear();

            return decryptedData;
        }