コード例 #1
0
	public static bool TestAlgorithms(SymmetricAlgorithm encAlgorithm, SymmetricAlgorithm decAlgorithm, int maxLength, int iterations)
	{
		Random rand = new Random();
		
		for (int i = 0; i < iterations; i++)
		{
			// Create random data, key, IV, mode
			//
			byte[] key = new byte[KeySizeBytes[rand.Next(KeySizeBytes.Length)]];
			rand.NextBytes(key);
			
			byte[] data = new byte[rand.Next(1, maxLength + 1)];
			rand.NextBytes(data);

			byte[] IV = new byte[BlockSizeBytes];
			rand.NextBytes(IV);
			
			// Encrypt the data
			//
			byte[] encryptedData;
			encAlgorithm.Key = key;
			encAlgorithm.IV = IV;

			ICryptoTransform transform = encAlgorithm.CreateEncryptor();
			encryptedData = transform.TransformFinalBlock(data, 0, data.Length);

			// Decrypt the data
			//
			byte[] decryptedData;
			decAlgorithm.Key = key;
			decAlgorithm.IV = IV;

			transform = decAlgorithm.CreateDecryptor();
			decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

			if (!CompareBytes(data, decryptedData))
			{
				Console.WriteLine("ERROR - roundtrip encrypt/decrypt failed!\n");
				Console.WriteLine("Encryption algorithm: {0}", encAlgorithm.ToString());
				Console.WriteLine("Decryption algorithm: {0}", decAlgorithm.ToString());
				Console.WriteLine("Original data: {0}", ByteArrayToString(data));
				Console.WriteLine("Roundtrip data: {0}", ByteArrayToString(decryptedData));
				Console.WriteLine("Key: {0}", ByteArrayToString(key));
				Console.WriteLine("IV: {0}", ByteArrayToString(IV));
				return false;
			}
		}

		return true;
	}
コード例 #2
0
ファイル: EncryptTools.cs プロジェクト: cleanmgr112/oms
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="cipherText">密文字符串</param>
        /// <returns>返回解密后的明文字符串</returns>
        public static string AESDecrypt(string showText, string Key)
        {
            showText = showText.Replace("%3d", "=").Replace(" ", "+").Replace("%2b", "+");

            byte[]             cipherText = Convert.FromBase64String(showText);
            SymmetricAlgorithm des        = Rijndael.Create();

            des.Key = Encoding.UTF8.GetBytes(Key);
            des.IV  = _aesKey;
            byte[] decryptBytes = new byte[cipherText.Length];
            using (MemoryStream ms = new MemoryStream(cipherText))
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cs.Read(decryptBytes, 0, decryptBytes.Length);
                    cs.Close();
                    ms.Close();
                }
            }
            return(Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""));   ///将字符串后尾的'\0'去掉
        }
コード例 #3
0
 /// <summary>
 /// 通用 SymmetricAlgorithm 解密函數. 可指定 (AES, DES, RC2, Rijndael, TripleDES) 演算法解密.
 /// </summary>
 /// <param name="symAlg"></param>
 /// <param name="baEncrypt"></param>
 /// <returns></returns>
 public static byte[] Decrypt(SymmetricAlgorithm symAlg, byte[] baEncrypt)
 {
     // usage:
     //AesCryptoServiceProvider aesCSP = new AesCryptoServiceProvider();
     //aesCSP.GenerateKey();
     //aesCSP.GenerateIV();
     //byte[] baEncrypt1 = Encrypt(aesCSP, baPlainText);
     //byte[] baDecrypt1 = Decrypt(aesCSP, baPlainText);
     try
     {
         ICryptoTransform transform1 = symAlg.CreateDecryptor();
         byte[]           baDecrypt  = transform1.TransformFinalBlock(baEncrypt, 0, baEncrypt.Length);
         symAlg.Clear();
         return(baDecrypt);
     }
     catch (Exception e1)
     {
         msError = e1.Message;
         return(null);
     }
 }
コード例 #4
0
ファイル: MD5DataEncryption.cs プロジェクト: TeTanT/SubmitBug
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="Value">要解密字符串</param>
        /// <returns>解密了的字符串</returns>
        public string DecryptString(string Value)
        {
            ICryptoTransform ct;
            MemoryStream     ms;
            CryptoStream     cs;

            byte[] byt;
            mCSP = new DESCryptoServiceProvider();
            ct   = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));

            byt = Convert.FromBase64String(Value);

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();

            cs.Close();

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
コード例 #5
0
 /// <summary>
 /// AES decoder
 /// </summary>
 /// <param name="str">string you want decode with Base64.</param>
 /// <returns>string </returns>
 public static string DecodeAES(string base64Str)
 {
     try {
         byte[]             cipherText = Convert.FromBase64String(base64Str);
         SymmetricAlgorithm des        = Rijndael.Create();
         des.Key = Encoding.UTF8.GetBytes(_aes_key);
         des.IV  = _aes_IV;
         byte[] decryptBytes = new byte[cipherText.Length];
         using (MemoryStream ms = new MemoryStream(cipherText)) {
             using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) {
                 cs.Read(decryptBytes, 0, decryptBytes.Length);
                 cs.Close();
                 ms.Close();
             }
         }
         return(Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""));                    ///remove \0
     } catch (Exception e) {
         XLAFInnerLog.Error(e.ToString());
     }
     return("");
 }
コード例 #6
0
        public override byte[] Decrypt(byte[] encryptedValue, byte[] initializationVector = null)
        {
            int dataOffset = 0;

            if (initializationVector == null)
            {
                initializationVector = new byte[algorithm.BlockSize / 8];
                Buffer.BlockCopy(encryptedValue, 0, initializationVector, 0, initializationVector.Length);
                dataOffset = initializationVector.Length;
            }

            using (var output = new MemoryStream())
            {
                using (var cryptoOutput = new CryptoStream(output, algorithm.CreateDecryptor(secretKey, initializationVector), CryptoStreamMode.Write))
                {
                    cryptoOutput.Write(encryptedValue, dataOffset, encryptedValue.Length - dataOffset);
                }

                return(output.ToArray());
            }
        }
コード例 #7
0
        /// <summary>
        /// 使用AES解密字符串,按128位处理key
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="key">秘钥,需要128位、256位.....</param>
        /// <returns>UTF8解密结果</returns>
        private static string AesDecrypt(string content, string key, bool autoHandle = true)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(key);
            if (autoHandle)
            {
                keyArray = GetAesKey(keyArray, key);
            }
            byte[] toEncryptArray = Convert.FromBase64String(content);

            SymmetricAlgorithm des = Aes.Create();

            des.Key     = keyArray;
            des.Mode    = CipherMode.ECB;
            des.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = des.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }
コード例 #8
0
 /// <summary>
 /// Decrypt
 /// </summary>
 /// <param name="securityTxt"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static string Decrypt(string securityTxt, string key, VECTOR vector)
 {
     try
     {
         var bytes = Convert.FromBase64String(securityTxt);
         SymmetricAlgorithm des = Rijndael.Create();
         des.Key = Encoding.Default.GetBytes(key);
         des.IV  = vector.ToByteArray();
         using (MemoryStream ms = new MemoryStream())
         {
             CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
             cs.Write(bytes, 0, bytes.Length);
             cs.FlushFinalBlock();
             return(Convert.ToBase64String(ms.ToArray()));
         }
     }
     catch (Exception)
     {
         return(string.Empty);
     }
 }
コード例 #9
0
        /// <summary>
        /// Decrypt string
        /// </summary>
        /// <param name="crypt_str"></param>
        /// <returns></returns>
        string Decrypt(string crypt_str)
        {
            // Получаем массив байт
            byte[] crypt_data = Convert.FromBase64String(crypt_str);

            // Алгоритм
            SymmetricAlgorithm sa_out = Rijndael.Create();
            // Объект для преобразования данных
            ICryptoTransform ct_out = sa_out.CreateDecryptor(
                (new PasswordDeriveBytes(encryPass, null)).GetBytes(16),
                new byte[16]);
            // Поток
            MemoryStream ms_out = new MemoryStream(crypt_data);
            // Расшифровываем поток
            CryptoStream cs_out = new CryptoStream(ms_out, ct_out, CryptoStreamMode.Read);
            // Создаем строку
            StreamReader sr_out     = new StreamReader(cs_out);
            string       source_out = sr_out.ReadToEnd();

            return(source_out);
        }
コード例 #10
0
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="Value">要解密的字符串</param>
        /// <returns>string</returns>
        public static string DecryptString(string Value)
        {
            ICryptoTransform ct; //定义基本的加密转换运算
            MemoryStream     ms; //定义内存流
            CryptoStream     cs; //定义将数据流链接到加密转换的流

            byte[] byt;
            ct = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV)); //用指定的密钥和初始化向量创建对称数据解密标准

            var bytes = StringToBytes(Value);

            Value = Convert.ToBase64String(bytes);

            byt = Convert.FromBase64String(Value); //将Value(Base 64)字符转换成字节数组
            ms  = new MemoryStream();
            cs  = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return(Encoding.UTF8.GetString(ms.ToArray())); //将字节数组中的所有字符解码为一个字符串
        }
コード例 #11
0
        public static string DecryptString(byte[] data)
        {
            SymmetricAlgorithm algo = SymmetricAlgorithm.Create();

            algo.Key = GetByte(Key);
            MemoryStream mStream = new MemoryStream();

            byte[] byteData = new byte[algo.IV.Length];
            Array.Copy(data, byteData, byteData.Length);
            algo.IV = byteData;
            int readFrom = 0;

            readFrom += algo.IV.Length;

            CryptoStream myCrypto = new CryptoStream(mStream, algo.CreateDecryptor(), CryptoStreamMode.Write);

            myCrypto.Write(data, readFrom, data.Length - readFrom);
            myCrypto.FlushFinalBlock();

            return(Encoding.UTF8.GetString(mStream.ToArray()));
        }
コード例 #12
0
ファイル: CryptoV2.cs プロジェクト: PangeaBogota/PEDIDOS
        public string DesEncriptar(string Value)
        {
            ICryptoTransform ct;
            MemoryStream     ms;
            CryptoStream     cs;

            byte[] byt;

            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);

            byt = Convert.FromBase64String(Value);

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();

            cs.Close();

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
コード例 #13
0
ファイル: AESHelper.cs プロジェクト: menglou/Building
        // AES 解密
        public string AESDecrypt(byte[] data)
        {
            SymmetricAlgorithm aes = Rijndael.Create();

            aes.Key     = keyArray;
            aes.IV      = ivArray;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            byte[] decryptBytes = new byte[data.Length];
            using (MemoryStream ms = new MemoryStream(data))
            {
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cs.Read(decryptBytes, 0, decryptBytes.Length);
                    cs.Close();
                    ms.Close();
                }
            }
            aes.Clear();
            return(System.Text.Encoding.Unicode.GetString(decryptBytes).Replace("\0", " "));
        }
コード例 #14
0
        public static string DecryptData(SymmetricAlgorithm aesAlgorithm, string value)
        {
            // Create a decryptor from the aes algorithm
            ICryptoTransform decryptor = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV);


            byte[] encryptedDataBuffer = Encoding.ASCII.GetBytes(value);

            // Create a memorystream to write the decrypted data in it
            using (MemoryStream ms = new MemoryStream(encryptedDataBuffer))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader reader = new StreamReader(cs))
                    {
                        // Reutrn all the data from the streamreader
                        return(reader.ReadLine());
                    }
                }
            }
        }
コード例 #15
0
ファイル: AES.cs プロジェクト: cardinals/Ultra.Base
        public static string Decrypt(string str)
        {
            SymmetricAlgorithm des = Rijndael.Create();
            var kb = Ultra.Web.Core.Common.HashDigest.StringDigest(PwdKey);

            des.Key = kb;
            des.IV  = _key1;
            var cipherText = Ultra.Web.Core.Common.ByteStringUtil.ByteArrayFromHexStr(str);

            byte[] decryptBytes = new byte[cipherText.Length];
            using (MemoryStream ms = new MemoryStream(cipherText))
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cs.Read(decryptBytes, 0, decryptBytes.Length);
                    cs.Close();
                    ms.Close();
                    return(Encoding.UTF8.GetString(decryptBytes));
                }
            }
        }
コード例 #16
0
        public override bool Decrypt(NetIncomingMessage msg)
        {
            int unEncLenBits = (int)msg.ReadUInt32();

            var ms = new MemoryStream(msg.m_data, 4, msg.LengthBytes - 4);
            var cs = new CryptoStream(ms, m_algorithm.CreateDecryptor(), CryptoStreamMode.Read);

            var byteLen = NetUtility.BytesToHoldBits(unEncLenBits);
            var result  = m_peer.GetStorage(byteLen);

            cs.Read(result, 0, byteLen);
            cs.Close();

            // TODO: recycle existing msg

            msg.m_data         = result;
            msg.m_bitLength    = unEncLenBits;
            msg.m_readPosition = 0;

            return(true);
        }
コード例 #17
0
        //Benton Stark    10-21-2013
        /// <summary>
        /// Decrypt ciphertext data using specified symmetric cipher and optional IV.
        /// </summary>
        /// <param name="algo">Symmetric cipher algorithm object.</param>
        /// <param name="key">Symmetric algorithm key.</param>
        /// <param name="iv">Optional IV value (can be null or empty byte array).</param>
        /// <param name="mode">Symmetric cipher block mode.</param>
        /// <param name="ciphertext">Ciphertext data to decrypt.</param>
        /// <returns>Cleartext data.</returns>
        public static byte[] Decrypt(SymmetricAlgorithm algo, byte[] key, byte[] iv, CipherMode mode, byte[] ciphertext)
        {
            if (algo == null)
            {
                throw new ArgumentNullException("algo");
            }
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (ciphertext == null)
            {
                throw new ArgumentNullException("cleartext");
            }
            algo.Mode = mode;
            ICryptoTransform d = algo.CreateDecryptor(key, iv);

            byte[] cleartext = new byte[ciphertext.Length];
            d.TransformBlock(ciphertext, 0, ciphertext.Length, cleartext, 0);
            return(cleartext);
        }
コード例 #18
0
ファイル: Form1.cs プロジェクト: megachelovek/ServerRSA
        private static byte[] DecryptBytes(SymmetricAlgorithm alg, byte[] message)
        {
            if ((message == null) || (message.Length == 0))
            {
                return(message);
            }

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

            using (var stream = new MemoryStream())
                using (var decryptor = alg.CreateDecryptor())
                    using (var encrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
                    {
                        encrypt.Write(message, 0, message.Length);
                        encrypt.FlushFinalBlock();
                        return(stream.ToArray());
                    }
        }
コード例 #19
0
        /// <summary>
        /// Decrypt the byte array.
        /// </summary>
        /// <param name="CypherText"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private static string decrypt(byte[] CypherText, SymmetricAlgorithm key)
        {
            // Create a memory stream to the passed buffer.
            MemoryStream ms = new MemoryStream(CypherText);

            // Create a CryptoStream using the memory stream and the
            // CSP DES key.
            CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);

            // Create a StreamReader for reading the stream.
            StreamReader sr = new StreamReader(encStream);

            // Read the stream as a string.
            string val = sr.ReadLine();

            // Close the streams.
            sr.Close();
            encStream.Close();
            ms.Close();
            return(val);
        }
コード例 #20
0
        /// <summary>
        /// Creates an <see cref="EncryptionReader"/> instance using the specified stream.
        /// </summary>
        /// <remarks>
        /// The <see cref="EncryptionReader"/> class is the preferred method to decrypt data.
        /// It is also more performant. The other decryption methods defer to the EncryptionReader
        /// class for actual decryption.
        /// </remarks>
        /// <param name="stream">The stream the encrypted data will be read from.</param>
        /// <returns>An instance of the <see cref="EncryptionReader"/> class.</returns>
        public EncryptionReader CreateStreamReader(Stream stream)
        {
            // Read salt from input stream
            byte[] salt = new byte[SaltLength];
            if (stream.Read(salt, 0, salt.Length) < SaltLength)
            {
                throw new ArgumentOutOfRangeException("Reached end of input stream before reading encryption metadata.");
            }
            // Create symmetric algorithm
            SymmetricAlgorithm algorithm = CreateAlgorithm();

            algorithm.Padding = PaddingMode.PKCS7;
            // Create key and IV
            byte[] key, iv;
            GenerateKeyAndIv(algorithm, salt, out key, out iv);
            // Create EncryptionReader
            ICryptoTransform decryptor = algorithm.CreateDecryptor(key, iv);
            CryptoStream     cs        = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);

            return(new EncryptionReader(algorithm, decryptor, stream));
        }
コード例 #21
0
 private byte[] \uE001(SymmetricAlgorithm \uE000, byte[] \uE001, byte[] \uE002, byte[] \uE003)
 {
     byte[] result;
     using (MemoryStream memoryStream = new MemoryStream())
     {
         ICryptoTransform transform = \uE000.CreateDecryptor(\uE002, \uE003);
         using (MemoryStream memoryStream2 = new MemoryStream(\uE001))
         {
             using (CryptoStream cryptoStream = new CryptoStream(memoryStream2, transform, CryptoStreamMode.Read))
             {
                 byte[] array = new byte[1024];
                 for (int i = cryptoStream.Read(array, 0, array.Length); i > 0; i = cryptoStream.Read(array, 0, array.Length))
                 {
                     memoryStream.Write(array, 0, i);
                 }
             }
         }
         result = memoryStream.ToArray();
     }
     return(result);
 }
コード例 #22
0
        /// <summary>
        /// 使用AES解密字符串,按128位处理key
        /// </summary>
        /// <param name="toDecryptArray">内容</param>
        /// <param name="key">秘钥,需要128位、256位.....</param>
        /// <returns>UTF8解密结果</returns>
        public static byte[] AesDecrypt(byte[] toDecryptArray, string key, bool autoHandle = true)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(key);
            if (autoHandle)
            {
                keyArray = GetAesKey(AESBit.Bit128, key);
            }

            SymmetricAlgorithm aes = Aes.Create();

            aes.Key     = keyArray;
            aes.Mode    = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = aes.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);

            //return Encoding.UTF8.GetString(resultArray);
            return(resultArray);
        }
コード例 #23
0
 /// <summary>
 /// Decrypt a string. Usage for license key
 /// </summary>
 /// <param name="text"></param>
 /// <returns>Decrypted sting or null if nota able to Decrypt</returns>
 public static string Decrypt(string text)
 {
     try
     {
         byte[] key = new byte[8] {
             1, 2, 3, 4, 5, 6, 7, 8
         };
         byte[] iv = new byte[8] {
             1, 2, 3, 4, 5, 6, 7, 8
         };
         SymmetricAlgorithm algorithm    = DES.Create();
         ICryptoTransform   transform    = algorithm.CreateDecryptor(key, iv);
         byte[]             inputbuffer  = Convert.FromBase64String(text);
         byte[]             outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length);
         return(Encoding.Unicode.GetString(outputBuffer));
     }
     catch (Exception)
     {
         return(null);
     }
 }
コード例 #24
0
ファイル: JlAes.cs プロジェクト: kangzhixing/JasonLib
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="cipherText">密文字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="encoding">编码格式</param>
        /// <returns>返回解密后的明文字符串</returns>
        public static string Decrypt(string cipherText, string key, Encoding encoding = null)
        {
            encoding = encoding ?? JlEncoding.Default;

            byte[]             byteCipherText = Convert.FromBase64String(cipherText);
            SymmetricAlgorithm des            = Rijndael.Create();

            des.Key = encoding.GetBytes(key);
            des.IV  = _key1;
            byte[] decryptBytes = new byte[cipherText.Length];
            using (MemoryStream ms = new MemoryStream(byteCipherText))
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cs.Read(decryptBytes, 0, decryptBytes.Length);
                    cs.Close();
                    ms.Close();
                }
            }
            return(Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""));   //将字符串后尾的'\0'去掉
        }
コード例 #25
0
        /// <summary>

        /// Desencripta o dado solicitado.

        /// </summary>

        /// <param name="cryptoText">Texto a ser descriptografado.</param>

        /// <returns>Texto descriptografado.</returns>

        public virtual string Decrypt(string textoCriptografado)
        {
            // Converte a base 64 string em num array de bytes

            byte[] cryptoByte = Convert.FromBase64String(textoCriptografado);

            byte[] keyByte = GetKey();


            // Seta a chave privada

            _algorithm.Key = keyByte;

            SetIV();


            // Interface de criptografia / Cria objeto de descriptografia

            ICryptoTransform cryptoTransform = _algorithm.CreateDecryptor();

            try
            {
                MemoryStream _memoryStream = new MemoryStream(cryptoByte, 0, cryptoByte.Length);


                CryptoStream _cryptoStream = new CryptoStream(_memoryStream, cryptoTransform, CryptoStreamMode.Read);


                // Busca resultado do CryptoStream

                StreamReader _streamReader = new StreamReader(_cryptoStream);

                return(_streamReader.ReadToEnd());
            }

            catch
            {
                return(null);
            }
        }
コード例 #26
0
        private string RODecryptString(string inStr, string inKey)
        {
            try
            {
                var    hasher        = new ROHasher(DesMD5);
                byte[] encryptedData = Convert.FromBase64String(inStr);
                byte   ver           = encryptedData[0];
                int    ivSize        = 0;
                if (ver == 1)
                {
                    ivSize = 8;
                }
                else if (ver == 2)
                {
                    ivSize = 16;
                }
                else
                {
                    throw new Exception("unsupported encryption version");
                }

                SymmetricAlgorithm cipher = ver == 1 ? (SymmetricAlgorithm) new TripleDESCryptoServiceProvider() : (SymmetricAlgorithm) new AesCryptoServiceProvider();

                try
                {
                    cipher.IV   = encryptedData.Skip(1).Take(ivSize).ToArray();
                    cipher.Mode = CipherMode.CBC;
                    cipher.Key  = hasher.ComputeHash(UTF8Encoding.UTF8.GetBytes(inKey)).Take(DesMD5 ? 16 : 32).ToArray();
                    string outStr = UTF8Encoding.UTF8.GetString(cipher.CreateDecryptor().TransformFinalBlock(encryptedData.Skip(1 + ivSize).ToArray(), 0, encryptedData.Length - (1 + ivSize)));
                    return(outStr);
                }
                catch
                {
                    return(null);
                }
            }
            catch {
                return(null);
            }
        }
コード例 #27
0
        /// <summary>
        /// Decriptografa a string
        /// </summary>
        /// <param name="pdstCriptografia">string criptografada</param>
        /// <returns>string decriptografada</returns>
        internal string Decriptografar(string p_strValorCriptografado)
        {
            //Declaração de variáveis
            MemoryStream       objStream       = null;
            CryptoStream       objCriptoStream = null;
            SymmetricAlgorithm objRijndael     = null;
            string             strCriptografia = null;

            byte[] aryString;

            //Objeto responsável pela manipulação dos dados
            objStream = new MemoryStream();

            //Recupera o valor do dataset
            strCriptografia = p_strValorCriptografado;

            //Monta uma array de bytes com o texto a ser criptografado
            aryString = Convert.FromBase64String(strCriptografia);

            //Cria o objeto de criptografia default "Rijndael"
            objRijndael = SymmetricAlgorithm.Create();

            //Atribui as chaves
            objRijndael.Key = Convert.FromBase64String(CriptografiaInfo.KEY);
            objRijndael.IV  = Convert.FromBase64String(CriptografiaInfo.IV);

            //Objeto responsável pela conversão
            objCriptoStream = new CryptoStream(objStream, objRijndael.CreateDecryptor(objRijndael.Key, objRijndael.IV), CryptoStreamMode.Write);

            //Decriptografa a string
            objCriptoStream.Write(aryString, 0, aryString.Length);
            objCriptoStream.FlushFinalBlock();
            objCriptoStream.Close();

            //Converte o retorno para o formato UTF-8
            strCriptografia = Encoding.UTF8.GetString(objStream.ToArray());

            //Retorna o dataset com o resultado
            return(strCriptografia);
        }
コード例 #28
0
ファイル: AesXts.cs プロジェクト: hmyit/xvdtool-1
        public AesXtsTransform(byte[] tweakBytes, byte[] dataAesKey, byte[] tweakAesKey, bool encrypt)
        {
            if (tweakBytes == null)
            {
                throw new InvalidDataException("Tweak bytes not provided");
            }
            if (dataAesKey == null)
            {
                throw new InvalidDataException("Data AES key not provided");
            }
            if (tweakAesKey == null)
            {
                throw new InvalidDataException("Tweak AES key not provided");
            }
            if (tweakBytes.Length != 16)
            {
                throw new InvalidDataException("Tweak bytes not 16 bytes");
            }
            if (dataAesKey.Length != 16)
            {
                throw new InvalidDataException("Data AES key not 16 bytes");
            }
            if (tweakAesKey.Length != 16)
            {
                throw new InvalidDataException("Tweak AES not 16 bytes");
            }

            _tweakBytes = tweakBytes;

            _symmetricAlgorithm         = Aes.Create();
            _symmetricAlgorithm.Padding = PaddingMode.None;
            _symmetricAlgorithm.Mode    = CipherMode.ECB;

            byte[] nullIv = new byte[16];
            _tweakEncryptor = _symmetricAlgorithm.CreateEncryptor(tweakAesKey, nullIv);
            _dataTransform  = encrypt ? _symmetricAlgorithm.CreateEncryptor(dataAesKey, nullIv) :
                              _symmetricAlgorithm.CreateDecryptor(dataAesKey, nullIv);

            BlockSize = _symmetricAlgorithm.BlockSize / 8;
        }
コード例 #29
0
ファイル: Form1.cs プロジェクト: davor-moslavac/OS_projekt
        public void aesDekriptiranje(string file, string decryptedFile)
        {
            FileStream fstreamU = File.OpenRead(file), fstreamO = File.OpenWrite(decryptedFile);

            MachineKeyStore = 128 * 1024;
            byte[] bytes = new byte[MachineKeyStore];
            int    read  = -1;

            SymmetricAlgorithm sma = Rijndael.Create();

            sma.Mode = CipherMode.ECB;

            TextReader tr        = new StreamReader("tajni_kljuc.txt");
            string     secretKey = tr.ReadLine();

            sma.Key = Convert.FromBase64String(secretKey);
            tr.Close();
            CryptoStream cin = new CryptoStream(fstreamU, sma.CreateDecryptor(), CryptoStreamMode.Read);

            BinaryReader br    = new BinaryReader(cin);
            long         lSize = br.ReadInt64();

            long numReads = lSize / MachineKeyStore;

            long slack = (long)lSize % MachineKeyStore;

            for (int i = 0; i < numReads; ++i)
            {
                read = cin.Read(bytes, 0, bytes.Length);
                fstreamO.Write(bytes, 0, read);
            }
            if (slack > 0)
            {
                read = cin.Read(bytes, 0, (int)slack);
                fstreamO.Write(bytes, 0, read);
            }
            fstreamO.Flush();
            fstreamO.Close();
            fstreamO.Dispose();
        }
コード例 #30
0
        public static MFTestResults Test_EncryptCsp(SymmetricAlgorithm csp1, SymmetricAlgorithm csp2, CryptokiAttribute[] keyTemplate)
        {
            bool testResult = false;

            try
            {
                string dataToEncrypt = "This is a simple message to be encrypted  dfjdfh ";

                byte[] data    = System.Text.UTF8Encoding.UTF8.GetBytes(dataToEncrypt);
                byte[] encData = null;
                byte[] newData = null;

                csp2.Key = CryptoKey.CreateObject(csp2.Session, keyTemplate) as CryptoKey;
                csp1.Key = CryptoKey.CreateObject(csp1.Session, keyTemplate) as CryptoKey;

                csp2.IV = csp1.IV;

                using (ICryptoTransform encr = csp1.CreateEncryptor())
                {
                    encData = encr.TransformFinalBlock(data, 0, data.Length);
                }
                using (ICryptoTransform decr = csp2.CreateDecryptor())
                {
                    newData = decr.TransformFinalBlock(encData, 0, encData.Length);
                }

                string res = new string(System.Text.UTF8Encoding.UTF8.GetChars(newData));

                //Debug.Print(dataToEncrypt);
                //Debug.Print(res);

                testResult = string.Compare(dataToEncrypt, res) == 0;
            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected Exception", ex);
            }

            return(testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
コード例 #31
0
 public string Decrypt(byte[] cipherbytes, string password)
 {
     byte[] plainbytes = null;
     try
     {
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, SALT);
         algorithm.Key     = pdb.GetBytes(32);
         algorithm.IV      = pdb.GetBytes(16);
         algorithm.Padding = PaddingMode.None;
         ms         = new MemoryStream(cipherbytes);
         cs         = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Read);
         plainbytes = new byte[cipherbytes.Length];
         cs.Read(plainbytes, 0, cipherbytes.Length);
         cs.Close();
         ms.Close();
     }
     catch (Exception)
     {
         MessageBox.Show("Decrypting error");
     }
     return(Encoding.UTF8.GetString(plainbytes));
 }
コード例 #32
0
ファイル: AESBlocks.cs プロジェクト: koson/.NETMF_for_LPC17xx
    private static bool TestRoundTrip(SymmetricAlgorithm testAlgorithm, SymmetricAlgorithm baseline, List<byte[]> data, out byte[] result)
    {
        result = null;

        try
        {
            byte[] testCipherValue;
            byte[] baselineCipherValue;

            using (MemoryStream testEncrypted = new MemoryStream())
            using (MemoryStream baselineEncrypted = new MemoryStream())
            {
                using (CryptoStream testEncryptor = new CryptoStream(testEncrypted, testAlgorithm.CreateEncryptor(), CryptoStreamMode.Write))
                using (CryptoStream baselineEncryptor = new CryptoStream(baselineEncrypted, baseline.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    foreach (byte[] blocks in data)
                    {
                        testEncryptor.Write(blocks, 0, blocks.Length);
                        baselineEncryptor.Write(blocks, 0, blocks.Length);
                    }

                    testEncryptor.Close();
                    baselineEncryptor.Close();

                    testCipherValue = testEncrypted.ToArray();
                    baselineCipherValue = baselineEncrypted.ToArray();
                }
            }

            byte[] testRoundtrip;
            byte[] baselineRoundtrip;

            using (MemoryStream testDecrypted = new MemoryStream())
            using (MemoryStream baselineDecrypted = new MemoryStream())
            {
                using (CryptoStream testDecryptor = new CryptoStream(testDecrypted, testAlgorithm.CreateDecryptor(), CryptoStreamMode.Write))
                using (CryptoStream baselineDecryptor = new CryptoStream(baselineDecrypted, baseline.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    testDecryptor.Write(baselineCipherValue, 0, baselineCipherValue.Length);
                    testDecryptor.Close();

                    baselineDecryptor.Write(testCipherValue, 0, testCipherValue.Length);
                    baselineDecryptor.Close();

                    testRoundtrip = testDecrypted.ToArray();
                    baselineRoundtrip = baselineDecrypted.ToArray();
                }
            }

            if (!CompareBytes(testRoundtrip, baselineRoundtrip))
            {
                Console.WriteLine("Roundtrip bytes do not match");
                Console.WriteLine("Test data: {0}", ByteArrayToString(testRoundtrip));
				Console.WriteLine("Baseline data: {0}", ByteArrayToString(baselineRoundtrip));
				Console.WriteLine("Key: {0}", ByteArrayToString(testAlgorithm.Key));
				Console.WriteLine("IV: {0}", ByteArrayToString(testAlgorithm.IV));
				Console.WriteLine("Cipher mode: {0}", testAlgorithm.Mode.ToString());
				Console.WriteLine("Padding mode: {0}", testAlgorithm.Padding.ToString());
				return false;
            }

            result = testRoundtrip;
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine("Got an exception, fail");
            Console.WriteLine(e);
            return false;
        }
    }
コード例 #33
0
ファイル: cryptperf.cs プロジェクト: symform/crimson
    static bool Test(SymmetricAlgorithm cipher, byte[] key, byte[] iv, byte[] input, byte[] expected)
    {
        cipher.Mode = CipherMode.ECB;
        cipher.KeySize = key.Length * 8;
        cipher.Padding = PaddingMode.Zeros;

        byte[] output = new byte [input.Length];
        ICryptoTransform encryptor = cipher.CreateEncryptor (key, iv);
        encryptor.TransformBlock (input, 0, input.Length, output, 0);
        if (!Compare (output, expected))
            return false;

        byte[] original = new byte [output.Length];
        ICryptoTransform decryptor = cipher.CreateDecryptor (key, iv);
        decryptor.TransformBlock (output, 0, output.Length, original, 0);
        return Compare (original, input);
    }
コード例 #34
0
	// Run a symmetric algorithm test.
	protected void RunSymmetric(SymmetricAlgorithm alg, byte[] key,
								byte[] plaintext, byte[] expected)
			{
				// Set up the algorithm the way we want.
				alg.Mode = CipherMode.ECB;
				alg.Padding = PaddingMode.None;

				// Create an encryptor and run the test forwards.
				ICryptoTransform encryptor = alg.CreateEncryptor(key, null);
				byte[] output = new byte [plaintext.Length * 2];
				byte[] tail;
				int len = encryptor.TransformBlock
						(plaintext, 0, plaintext.Length,
						 output, 0);
				AssertEquals("ECB encrypt length mismatch",
							 len, expected.Length);
				tail = encryptor.TransformFinalBlock
						(plaintext, 0, 0);
				AssertNotNull("ECB encrypt tail should be non-null");
				AssertEquals("ECB encrypt tail should be zero length",
							 tail.Length, 0);
				if(!IdenticalBlock(expected, 0, output, 0,
								   expected.Length))
				{
					Fail("did not encrypt to the expected output");
				}
				encryptor.Dispose();

				// Create a decryptor and run the test backwards.
				ICryptoTransform decryptor = alg.CreateDecryptor(key, null);
				len = decryptor.TransformBlock
						(expected, 0, expected.Length, output, 0);
				AssertEquals("ECB decrypt length mismatch",
							 len, expected.Length);
				tail = decryptor.TransformFinalBlock
						(expected, 0, 0);
				AssertNotNull("ECB decrypt tail should be non-null");
				AssertEquals("ECB decrypt tail should be zero length",
							 tail.Length, 0);
				if(!IdenticalBlock(plaintext, 0, output, 0,
								   plaintext.Length))
				{
					Fail("did not decrypt to the original plaintext");
				}
				decryptor.Dispose();
			}
コード例 #35
0
	// Run a cipher mode test.
	private void RunModeTest(SymmetricAlgorithm alg, CipherMode mode,
							 PaddingMode padding, String input)
			{
				// Set the algorithm modes.
				alg.Mode = mode;
				alg.Padding = padding;

				// Get the raw and padded versions of the input.
				byte[] rawInput = Encoding.ASCII.GetBytes(input);
				byte[] paddedInput = StringToBytes(input, alg);

				// Generate key and IV values.
				byte[] key = CreateKey(alg);
				byte[] iv = CreateIV(alg);

				// Encrypt the raw input in the selected mode.
				int size = alg.BlockSize / 8;
				int cutoff = rawInput.Length - rawInput.Length % size;
				ICryptoTransform encryptor;
				encryptor = alg.CreateEncryptor(key, iv);
				Assert(GetError("encryptor cannot transform multiple blocks",
								alg, input),
					   encryptor.CanTransformMultipleBlocks);
				if(mode == CipherMode.ECB || mode == CipherMode.CBC)
				{
					AssertEquals(GetError("encryptor has wrong input size",
										  alg, input),
								 size, encryptor.InputBlockSize);
					AssertEquals(GetError("encryptor has wrong output size",
										  alg, input),
								 size, encryptor.OutputBlockSize);
				}
				else
				{
					AssertEquals(GetError("encryptor has wrong input size",
										  alg, input),
								 1, encryptor.InputBlockSize);
					AssertEquals(GetError("encryptor has wrong output size",
										  alg, input),
								 1, encryptor.OutputBlockSize);
				}
				byte[] rawOutput = new byte [rawInput.Length + 256];
				int len = encryptor.TransformBlock
					(rawInput, 0, cutoff, rawOutput, 0);
				byte[] rawTail = encryptor.TransformFinalBlock
					(rawInput, cutoff, rawInput.Length - cutoff);
				Array.Copy(rawTail, 0, rawOutput, len, rawTail.Length);
				len += rawTail.Length;
				((IDisposable)encryptor).Dispose();

				// Reverse the ciphertext back to the original.
				cutoff = len - len % size;
				ICryptoTransform decryptor;
				decryptor = alg.CreateDecryptor(key, iv);
				Assert(GetError("decryptor cannot transform multiple blocks",
								alg, input),
					   decryptor.CanTransformMultipleBlocks);
				if(mode == CipherMode.ECB || mode == CipherMode.CBC)
				{
					AssertEquals(GetError("decryptor has wrong input size",
										  alg, input),
								 size, decryptor.InputBlockSize);
					AssertEquals(GetError("decryptor has wrong output size",
										  alg, input),
								 size, decryptor.OutputBlockSize);
				}
				else
				{
					AssertEquals(GetError("decryptor has wrong input size",
										  alg, input),
								 1, decryptor.InputBlockSize);
					AssertEquals(GetError("decryptor has wrong output size",
										  alg, input),
								 1, decryptor.OutputBlockSize);
				}
				byte[] rawReverse = new byte [rawInput.Length + 256];
				int rlen = decryptor.TransformBlock
					(rawOutput, 0, cutoff, rawReverse, 0);
				rawTail = decryptor.TransformFinalBlock
					(rawOutput, cutoff, len - cutoff);
				Array.Copy(rawTail, 0, rawReverse, rlen, rawTail.Length);
				rlen += rawTail.Length;
				((IDisposable)decryptor).Dispose();

				// Compare the reversed plaintext with the original.
				if(padding != PaddingMode.None)
				{
					AssertEquals(GetError
							("reversed plaintext has incorrect length",
							 alg, input), rawInput.Length, rlen);
					if(!IdenticalBlock(rawInput, 0, rawReverse, 0, rlen))
					{
						Fail(GetError
							("reversed plaintext is not the same as original",
							 alg, input));
					}
				}
				else
				{
					if(rawInput.Length > rlen)
					{
						Fail(GetError
							("reversed plaintext has incorrect length",
							 alg, input));
					}
					if(!IdenticalBlock(rawInput, 0, rawReverse, 0,
									   rawInput.Length))
					{
						Fail(GetError
							("reversed plaintext is not the same as original",
							 alg, input));
					}
				}

				// Encrypt the padded plaintext using a primitive
				// algorithm simulation to verify the expected output.
				byte[] paddedOutput;
				switch(mode)
				{
					case CipherMode.ECB:
					{
						paddedOutput = DoECB(paddedInput, alg, key);
					}
					break;

					case CipherMode.CBC:
					{
						paddedOutput = DoCBC(paddedInput, alg, key, iv);
					}
					break;

					case CipherMode.OFB:
					{
						paddedOutput = DoOFB(paddedInput, alg, key, iv);
					}
					break;

					case CipherMode.CFB:
					{
						paddedOutput = DoCFB(paddedInput, alg, key, iv);
					}
					break;

					case CipherMode.CTS:
					default:
					{
						paddedOutput = DoCTS(paddedInput, alg, key, iv);
					}
					break;
				}

				// Compare the actual output with the expected output.
				AssertEquals(GetError("ciphertext has incorrect length",
									  alg, input),
							 paddedOutput.Length, len);
				if(!IdenticalBlock(paddedOutput, 0, rawOutput, 0, len))
				{
					Fail(GetError("ciphertext was not the expected value",
								  alg, input));
				}
			}