Ejemplo n.º 1
0
        // -------------------------------------------------------------------------------

        /// <summary>
        /// SimpleDecrypt the ciphertext.
        /// </summary>
        /// <param name="ciphertext">The ciphertext to be decrypted.</param>
        /// <returns>The decrypted ciphertext (-> plaintext).</returns>
        private byte[] SimpleDecrypt(byte[] ciphertext)
        {
            byte[] plaintext = null;

            string base64String = ByteArrayToAnsiString(ciphertext);

            byte[] binaryData = Convert.FromBase64String(base64String);

            MemoryStream memoryStream = new MemoryStream(binaryData, 16, binaryData.Length - 16);

            byte[] IV = new byte[16];

            // get the initialization vector
            for (int i = 0; i < 16; i++)
            {
                IV[i] = binaryData[i];
            }

            //Creates the default implementation, which is RijndaelManaged.
            SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
            // creates a symmetric decryptor object with the specified Key and initialization vector (IV).
            ICryptoTransform decryptor = rijn.CreateDecryptor(this.key, IV);

            // prepare the Crypto Stream
            CryptoStream encryptedData = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

            // decrypt ciphertext
            MemoryStream decryptedData = this.GetBytes(encryptedData);

            decryptedData.Position = 0;

            plaintext = decryptedData.ToArray();

            // Speicher frei geben
            memoryStream.Close();
            decryptedData.Close();
            encryptedData.Close();
            decryptor.Dispose();
            rijn.Clear();

            return(plaintext);
        }
        public SymmetricCryptoKey(Stream s)
        {
            BinaryReader bR = new BinaryReader(s);

            if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "SK")
            {
                throw new CryptoException("Invalid SymmetricCryptoKey format.");
            }

            byte version = bR.ReadByte();

            switch (version) //version
            {
            case 1:
            case 2:
                //algorithm
                _cryptoAlgo = (SymmetricEncryptionAlgorithm)bR.ReadByte();
                _symAlgo    = SymmetricAlgorithm.Create(_cryptoAlgo.ToString());

                //key
                _symAlgo.Key = bR.ReadBytes(bR.ReadByte());

                //IV
                _symAlgo.IV = bR.ReadBytes(bR.ReadByte());

                //padding
                if (version == 1)
                {
                    _symAlgo.Padding = PaddingMode.ISO10126;
                }
                else
                {
                    _symAlgo.Padding = (PaddingMode)bR.ReadByte();
                }

                _symAlgo.Mode = CipherMode.CBC;
                break;

            default:
                throw new CryptoException("SymmetricCryptoKey format version not supported.");
            }
        }
Ejemplo n.º 3
0
        /// <summary>Creates a SymmetricAlgorithm used by this SPI.</summary>
        public SymmetricAlgorithm CreateSymmetricAlgorithm()
        {
            SymmetricAlgorithm sa = null;

            if (Encryptor.Equals("NullEncryption"))
            {
                sa = new NullEncryption();
            }
            else
            {
                sa = SymmetricAlgorithm.Create(Encryptor);
            }

            if (sa == null)
            {
                throw new Exception("Unsupported encryption algorithm: " + Encryptor);
            }

            return(sa);
        }
Ejemplo n.º 4
0
        static byte[] SymmetricEncryption(string message)
        {
            //Encode string as Bytes
            byte[] messgeByte = Encoding.UTF8.GetBytes(message);

            //Create SymmetricAlgorithm object
            SymmetricAlgorithm symmAlgo = SymmetricAlgorithm.Create();

            //Create encryptor using the SymmetricAlgorithm object
            ICryptoTransform encryptor = symmAlgo.CreateEncryptor(symmAlgo.Key, symmAlgo.IV);

            //Transform Byte encoding message to encryted byte
            byte[] encryptedByte = encryptor.TransformFinalBlock(messgeByte, 0, messgeByte.Length);


            //Encoding encypted byte as string for delivery
            //string encryptedStr = Encoding.UTF8.GetString(encryptedByte);

            return(encryptedByte);
        }
Ejemplo n.º 5
0
        /*
         * public static HttpCookie EncodeCookie(HttpCookie cookie)
         * {
         *      if (cookie == null) return null;
         *
         *      char[] chars = { ',' };
         *      var splits = ConfigurationManager.AppSettings["CookieEncodingKey"].Split(chars);
         *      var AlgorithmName = splits[0];
         *      var Key = new byte[Int32.Parse(splits[1])];// = KEY_64;
         *      for (int i = 2; i < Key.Length + 2; i++)
         *              Key[i - 2] = byte.Parse(splits[i].Trim());
         *
         *      var eCookie = new HttpCookie(cookie.Name);
         *
         *      for (int i = 0; i < cookie.Values.Count; i++)
         *      {
         *              var value = HttpContext.Current.Server.UrlEncode(Encode(cookie.Values[i], Key, AlgorithmName));
         *              var name = HttpContext.Current.Server.UrlEncode(Encode(cookie.Values.GetKey(i), Key, AlgorithmName));
         *              eCookie.Values.Set(name, value);
         *      }
         *      return eCookie;
         * }
         */

        public static string Encode(string value, Byte[] key, string AlgorithmName)
        {
            var ClearData = System.Text.Encoding.UTF8.GetBytes(value);

            var Algorithm = SymmetricAlgorithm.Create(AlgorithmName);

            Algorithm.Key = key;
            var Target = new MemoryStream();

            Algorithm.GenerateIV();
            Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);

            using (var cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(ClearData, 0, ClearData.Length);
                cs.FlushFinalBlock();

                return(Convert.ToBase64String(Target.GetBuffer(), 0, (int)Target.Length));
            }
        }
Ejemplo n.º 6
0
 public static BigInteger Transform(string name, bool encrypt, BigInteger key, BigInteger message)
 {
     using (var cipher = SymmetricAlgorithm.Create(name))
     {
         var k = key.GetBytes();
         //Credit goes to ichoes (https://github.com/ichoes) for fixing this issue (https://github.com/sgbj/Dukpt.NET/issues/5)
         //gets the next multiple of 8
         cipher.Key     = new byte[Math.Max(0, GetNearestWholeMultiple(k.Length, 8) - k.Length)].Concat(key.GetBytes()).ToArray();
         cipher.IV      = new byte[8];
         cipher.Mode    = CipherMode.CBC;
         cipher.Padding = PaddingMode.Zeros;
         using (var crypto = encrypt ? cipher.CreateEncryptor() : cipher.CreateDecryptor())
         {
             var data = message.GetBytes();
             //Added the GetNearestWholeMultiple here.
             data = new byte[Math.Max(0, GetNearestWholeMultiple(data.Length, 8) - data.Length)].Concat(message.GetBytes()).ToArray();
             return(BigInt.FromBytes(crypto.TransformFinalBlock(data, 0, data.Length)));
         }
     }
 }
Ejemplo n.º 7
0
        public static SymmetricAlgorithm GetSymmetricCryptoService(SymmetricProvider netSelected)
        {
            SymmetricAlgorithm algorithm = new DESCryptoServiceProvider();

            switch (netSelected)
            {
            case SymmetricProvider.Default:
                return(SymmetricAlgorithm.Create());

            case SymmetricProvider.DES:
                return(new DESCryptoServiceProvider());

            case SymmetricProvider.RC2:
                return(new RC2CryptoServiceProvider());

            case SymmetricProvider.Rijndael:
                return(new RijndaelManaged());
            }
            return(algorithm);
        }
Ejemplo n.º 8
0
        public static byte[] EncryptString(string data)
        {
            byte[]             byteData = GetByte(data);
            SymmetricAlgorithm algo     = SymmetricAlgorithm.Create();

            algo.Key = GetByte(Key);
            algo.GenerateIV();

            MemoryStream mStream = new MemoryStream();

            mStream.Write(algo.IV, 0, algo.IV.Length);

            CryptoStream cStream = new CryptoStream(mStream,
                                                    algo.CreateEncryptor(), CryptoStreamMode.Write);

            cStream.Write(byteData, 0, byteData.Length);
            cStream.FlushFinalBlock();

            return(mStream.ToArray());
        }
Ejemplo n.º 9
0
        public static string EncryptString(this string clearText)
        {
            if (string.IsNullOrWhiteSpace(clearText))
            {
                throw new ArgumentNullException("clearText");
            }

            byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText);

            using (var rijn = SymmetricAlgorithm.Create())
                using (var memory = new MemoryStream())
                {
                    using (var cs = new CryptoStream(memory, rijn.CreateEncryptor(keyString, IVString), CryptoStreamMode.Write))
                    {
                        cs.Write(clearTextBytes, 0, clearTextBytes.Length);
                        cs.Close();
                    }
                    return(Convert.ToBase64String(memory.ToArray()));
                }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the cryptographic stream by using the given stream for reading encrypted data. (Decrypting)
        /// </summary>
        /// <param name="stream">The raw stream</param>
        /// <param name="password">The decryption password</param>
        /// <returns>A cryptographic stream wrapper which has an underlying <see cref="CryptoStream"/> for reading encrypted data</returns>
        public virtual SaveSystemCryptoStream GetReadStream(IStorageStream stream, string password)
        {
            var alg = SymmetricAlgorithm.Create(this.AlgorithmName);

            alg.Mode    = CipherMode.CBC;
            alg.Padding = PaddingMode.PKCS7;
            var thisIV = new byte[ivSize];

            // Read the IV from the stream
            stream.UnderlyingStream.Read(thisIV, 0, ivSize);
            alg.IV = thisIV;

            var key = new Rfc2898DeriveBytes(password, alg.IV, pwIterations);

            alg.Key = key.GetBytes(keySize);

            var decryptor = alg.CreateDecryptor();

            return(new SaveSystemSymmetricCryptoStream(new CryptoStream(stream.UnderlyingStream, decryptor, CryptoStreamMode.Read), alg, decryptor));
        }
Ejemplo n.º 11
0
        public static string EncryptString(string clearText)
        {
            if (clearText == null)
            {
                return("");
            }

            byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText);

            SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(m_cryptKey, m_initVector), CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);
            cs.Close();

            return(Convert.ToBase64String(ms.ToArray()));
        }
Ejemplo n.º 12
0
        public static string DecryptString(string EncryptedText)
        {
            string retval;

            byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

            using (MemoryStream ms = new MemoryStream())
            {
                SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
                using (CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write))
                {
                    cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

                    cs.Close();
                }
                retval = Encoding.UTF8.GetString(ms.ToArray());
            }

            return(retval);
        }
Ejemplo n.º 13
0
        public CryptoHelper(string algorithmName, string key)
        {
            SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithmName);

            byte[] bKeys = new byte[24];
            byte[] sssss = Encoding.Unicode.GetBytes(key);
            for (int lvi = 0; lvi < 24; lvi++)
            {
                if (lvi >= sssss.Length)
                {
                    break;
                }
                bKeys[lvi] = sssss[lvi];
            }
            provider.Key = bKeys;
            provider.IV  = new byte[] { 0x23, 0x54, 0xC6, 0x68, 0x90, 0xAB, 0xBD, 0xEF };

            encryptor = provider.CreateEncryptor();
            decryptor = provider.CreateDecryptor();
        }
Ejemplo n.º 14
0
        public static byte[] EncryptData(string data, string keyFile)
        {
            byte[] ClearData = Encoding.UTF8.GetBytes(data);

            SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);

            ReadKey(Algorithm, keyFile);

            MemoryStream Target = new MemoryStream();

            Algorithm.GenerateIV();
            Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);

            CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);

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

            return(Target.ToArray());
        }
Ejemplo n.º 15
0
        private static string EncryptString(string clearText)
        {
            if (!string.IsNullOrWhiteSpace(clearText))
            {
                var clearTextBytes = Encoding.UTF8.GetBytes(clearText);

                var rijn  = SymmetricAlgorithm.Create();
                var ms    = new MemoryStream();
                var rgbIv = Encoding.ASCII.GetBytes("lkjhfuefvbhjoiwq");
                var key   = Encoding.ASCII.GetBytes("oiturekjhbkjvhguzgweriuzguzrgkac");
                var cs    = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIv), CryptoStreamMode.Write);

                cs.Write(clearTextBytes, 0, clearTextBytes.Length);

                cs.Close();

                return(Convert.ToBase64String(ms.ToArray()));
            }
            return(null);
        }
Ejemplo n.º 16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var token   = HttpContext.Current.Request.Form["Token"];
            var resCode = int.Parse(HttpContext.Current.Request.Form["ResCode"]);

            if (resCode == 0)
            {
                var dataBytes = Encoding.UTF8.GetBytes(token);

                var symmetric = SymmetricAlgorithm.Create("TripleDes");
                symmetric.Mode    = CipherMode.ECB;
                symmetric.Padding = PaddingMode.PKCS7;

                var encryptor = symmetric.CreateEncryptor(Convert.FromBase64String("fFnSgtgWppg17ntADfoepx9uL6Dl16Bx"), new byte[8]);

                var signedData = Convert.ToBase64String(encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length));


                var data = new
                {
                    token    = token,
                    SignData = signedData
                };

                var ipgUri = "https://sadad.shaparak.ir/api/v0/AdviceEx/Verify";

                var res = CallApi <VerifyResultData>(ipgUri, data);
                if (res != null && res.Result != null)
                {
                    if (res.Result.ResCode == "0")
                    {
                        var result = res.Result;
                        res.Result.Succeed = true;
                        Message.Text       = res.Result.Description;
                        ResCode.Text       = res.Result.ResCode;
                        RRN.Text           = res.Result.RetrivalRefNo;
                        Trace.Text         = res.Result.SystemTraceNo;
                    }
                }
            }
        }
        public InsecureEncryptionAlgorithm()
        {
            using (var tripleDES = new MyTripleDESCryptoServiceProvider()) //Noncompliant {{Use the recommended AES (Advanced Encryption Standard) instead.}}
//                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            {
                //...
            }

            using (var des = new DESCryptoServiceProvider()) //Noncompliant
            {
                //...
            }

            using (TripleDES TripleDESalg = TripleDES.Create()) //Noncompliant
//                                          ^^^^^^^^^^^^^^^^^^
            {
            }
            using (var des = DES.Create("fgdsgsdfgsd")) //Noncompliant
            {
            }

            using (var aes = new AesCryptoServiceProvider())
            {
                //...
            }
            using (var rc2 = new RC2CryptoServiceProvider()) // Noncompliant
            {
            }

            using (var rc2 = RC2.Create()) // Noncompliant
            {
            }

            SymmetricAlgorithm des1 = SymmetricAlgorithm.Create("DES"); //Noncompliant

            des1 = SymmetricAlgorithm.Create("TripleDES");              //Noncompliant
            des1 = SymmetricAlgorithm.Create("3DES");                   //Noncompliant
            var rc2 = SymmetricAlgorithm.Create("RC2");                 // Noncompliant

            var crypto = CryptoConfig.CreateFromName("DES");            // Noncompliant
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Converts a secure string back to the object tree it represents, using
        /// a custom <see cref="Deserializer"/> and <see cref="SignatureChecker"/>.
        /// </summary>
        /// <param name="secureString">the secure string to be converted back to an
        /// object tree.</param>
        /// <param name="encryptionKey">the key to use to decrypt the ciphertext</param>
        /// <param name="validationKey">ignored</param>
        /// <param name="encryptionAlgorithm">the name of the encryption algorithm to use, null means use default</param>
        /// <param name="validationAlgorithm">the name of the signing algorithm to use, null means use default</param>
        /// <param name="deserializer">a <see cref="Deserializer"/> delegate from the
        /// root object of the object tree that can recreate the object tree from a
        /// <see cref="Stream"/> of serialized bytes.</param>
        /// <param name="sigChecker">a <see cref="SignatureChecker"/> delegate that
        /// compares an actual signature to the expected signature, throwin an exception
        /// if they don't match.</param>
        /// <remarks>The encryption key and algorithms must have
        /// the same values as they did when <see cref="Protect(Serializer, byte[], byte[])"/> was called or
        /// an exception will occur.</remarks>
        public static void Unprotect(string secureString, byte[] encryptionKey, byte[] unused, string encryptionAlgorithm, string validationAlgorithm, Deserializer deserializer, SignatureChecker sigChecker)
        {
            byte[]       secureBytes  = Convert.FromBase64String(secureString);
            MemoryStream secureStream = new MemoryStream(secureBytes);
            BinaryReader binaryReader = new BinaryReader(secureStream);

            byte[] actualHash = binaryReader.ReadBytes(binaryReader.ReadByte());
            byte[] iv         = binaryReader.ReadBytes(binaryReader.ReadByte());
            byte[] cipherText = binaryReader.ReadBytes((int)(secureStream.Length - secureStream.Position));

            // Verify the hash
            HashAlgorithm hashAlgorithm
                = validationAlgorithm != null
                ? HashAlgorithm.Create(validationAlgorithm)
                : HashAlgorithm.Create();

            byte[] expectedHash = hashAlgorithm.ComputeHash(cipherText);
            sigChecker(actualHash, expectedHash);

            // Decrypt the ciphertext
            MemoryStream       cipherTextStream = new MemoryStream(cipherText);
            SymmetricAlgorithm cipher
                = encryptionAlgorithm != null
                ? SymmetricAlgorithm.Create(encryptionAlgorithm)
                : SymmetricAlgorithm.Create();

            cipher.Mode    = CipherMode.CBC;
            cipher.Padding = PaddingMode.PKCS7;
            cipher.Key     = encryptionKey;
            cipher.IV      = iv;
            CryptoStream cryptoStream = new CryptoStream(cipherTextStream, cipher.CreateDecryptor(), CryptoStreamMode.Read);

            try
            {
                deserializer(cryptoStream);
            }
            finally
            {
                cryptoStream.Close();
            }
        }
        public VerifyResult Refund()
        {
            var result = new VerifyResult();

            if (Token == null)
            {
                result.Description = "توکن امنیتی در سیستم وجود ندارد.";
                return(result);
            }

            var dataBytes = Encoding.UTF8.GetBytes(Token);

            var symmetric = SymmetricAlgorithm.Create("TripleDes");

            symmetric.Mode    = CipherMode.ECB;
            symmetric.Padding = PaddingMode.PKCS7;

            var encryptor = symmetric.CreateEncryptor(Convert.FromBase64String(TransactionKey), new byte[8]);

            var signedData = Convert.ToBase64String(encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length));

            var data = new
            {
                Token    = Token,
                SignData = signedData
            };

            var res = CallApi <VerifyResultData>(RestVerifyWebservice, data);

            if (res.Result != null)
            {
                result.Amount  = long.Parse(res.Result.Amount);
                result.Status  = res.Result.ResCode;
                result.OrderId = res.Result.OrderId != null?long.Parse(res.Result.OrderId) : 0;

                result.RefrenceNumber   = res.Result.SystemTraceNo;
                result.BankReciptNumber = res.Result.RetrivalRefNo;
                result.Description      = GetDescription(1002, int.Parse(result.Status));
            }
            return(result);
        }
Ejemplo n.º 20
0
        public SymmetricAlgorithm GetCipher(int algorithm, int mode, /*SecretKey key,*/ byte[] key, byte[] vec)
        {
            try
            {
                string name  = null;
                string chain = null;
                if (algorithm == EncryptionHeader.ALGORITHM_AES_128 ||
                    algorithm == EncryptionHeader.ALGORITHM_AES_192 ||
                    algorithm == EncryptionHeader.ALGORITHM_AES_256)
                {
                    name = "AES";
                }

                if (mode == EncryptionHeader.MODE_CBC)
                {
                    chain = "CBC";
                }
                else if (mode == EncryptionHeader.MODE_CFB)
                {
                    chain = "CFB";
                }

                //SymmetricAlgorithm cipher = SymmetricAlgorithm.Create(name + "/" + chain + "/Nopadding");
#if NETSTANDARD2_0
                var cipher = Aes.Create();
#else
                SymmetricAlgorithm cipher = SymmetricAlgorithm.Create();
#endif
                cipher.Key     = key;
                cipher.IV      = vec;
                cipher.Padding = PaddingMode.None;
                cipher.Mode    = chain == "CBC" ? CipherMode.CBC : CipherMode.CFB;
                // cipher.Key = ;
                //cipher.IV =
                return(cipher);
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 21
0
        public EncryptedData Encrypt(XmlElement inputElement, string keyName)
        {
            // There are two keys of note here.
            // 1) KeyAlg: the key-encryption-key is used to wrap a key.  The keyName
            //    parameter will give us the KEK.
            // 2) SymAlg: A 256-bit AES key will be generated to encrypt the contents.
            //    This key will be wrapped using the KEK.

            SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create("Rijndael");

            symAlg.KeySize = 256;
            symAlg.GenerateKey();
            symAlg.GenerateIV();

            EncryptedData encryptedData = new EncryptedData();
            EncryptedKey  encryptedKey  = new EncryptedKey();

            object keyAlg = keyNameMapping [keyName];

            encryptedKey.EncryptionMethod = new EncryptionMethod(GetKeyWrapAlgorithmUri(keyAlg));

            if (keyAlg is RSA)
            {
                encryptedKey.CipherData = new CipherData(EncryptKey(symAlg.Key, (RSA)keyAlg, false));
            }
            else
            {
                encryptedKey.CipherData = new CipherData(EncryptKey(symAlg.Key, (SymmetricAlgorithm)keyAlg));
            }

            encryptedKey.KeyInfo = new KeyInfo();
            encryptedKey.KeyInfo.AddClause(new KeyInfoName(keyName));

            encryptedData.Type             = XmlEncElementUrl;
            encryptedData.EncryptionMethod = new EncryptionMethod(GetAlgorithmUri(symAlg));
            encryptedData.KeyInfo          = new KeyInfo();
            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));
            encryptedData.CipherData = new CipherData(EncryptData(inputElement, symAlg, false));

            return(encryptedData);
        }
Ejemplo n.º 22
0
        public static string DecryptString(this string encryptedText)
        {
            if (string.IsNullOrWhiteSpace(encryptedText))
            {
                throw new ArgumentNullException("encryptedText");
            }

            byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText);

            using (var rijn = SymmetricAlgorithm.Create())
                using (var memory = new MemoryStream())
                {
                    using (var cs = new CryptoStream(memory, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write))
                    {
                        cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
                        cs.Close();
                    }

                    return(Encoding.UTF8.GetString(memory.ToArray()));
                }
        }
Ejemplo n.º 23
0
        public static string DecryptString(string EncryptedText)
        {
            byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

            var ms = new MemoryStream();

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


            byte[] rgbIV = Encoding.ASCII.GetBytes("ayojvlzmdalyglrj");
            byte[] key   = Encoding.ASCII.GetBytes("hlxilkqbbhczfeultgbskdmaunivmfuo");

            var cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
                                      CryptoStreamMode.Write);

            cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

            cs.Close();

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
Ejemplo n.º 24
0
        //DecryptString
        //Make sure you use the same keys you used to encrypt the string
        public string DecryptString(string EncryptedText, string key1, string key2)
        {
            byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


            byte[] rgbIV = Encoding.ASCII.GetBytes(key1);
            byte[] key   = Encoding.ASCII.GetBytes(key2);

            CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
                                               CryptoStreamMode.Write);

            cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

            cs.Close();

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
Ejemplo n.º 25
0
        /// <summary>
        ///     A simply decryption, can be used to store passwords
        /// </summary>
        /// <param name="encryptedText">a base64 encoded encrypted string</param>
        /// <returns>Decrypeted text</returns>
        private static string Decrypt(string encryptedText)
        {
            string returnValue;
            var    encryptedTextBytes = Convert.FromBase64String(encryptedText);

            using (var symmetricAlgorithm = SymmetricAlgorithm.Create(Algorithm))
            {
                var memoryStream = new MemoryStream();
                var rgbIv        = Encoding.ASCII.GetBytes(RgbIv);
                var key          = Encoding.ASCII.GetBytes(RgbKey);

                using (var cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateDecryptor(key, rgbIv), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    returnValue = Encoding.ASCII.GetString(memoryStream.ToArray());
                }
            }

            return(returnValue);
        }
Ejemplo n.º 26
0
        public static string EncryptString(string ClearText)
        {
            string retval;

            byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write))
                {
                    cs.Write(clearTextBytes, 0, clearTextBytes.Length);

                    cs.Close();
                }
                retval = Convert.ToBase64String(ms.ToArray());
            }

            return(retval);
        }
Ejemplo n.º 27
0
        private byte[] EncryptData(int choice, byte[] Key, byte[] IV, byte[] toEncryptData)
        {
            try
            {
                SymmetricAlgorithm crypt     = SymmetricAlgorithm.Create(sma[choice]);
                ICryptoTransform   transform = crypt.CreateEncryptor(Key, IV);//这里不一样

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                //Convert the data to a byte array.
                //Write all data to the crypto stream and flush it.
                cs.Write(toEncryptData, 0, toEncryptData.Length);
                cs.FlushFinalBlock();
                //Get encrypted array of bytes.
                return(ms.ToArray());
            }
            catch
            {
                throw new CryptographicException("加密出现失误,请重新检查输入!");
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Return the available key sizes for the given algorithim
        /// </summary>
        /// <param name="selectedAlgorithim"></param>
        /// <returns></returns>
        public ObservableCollection <int> GetKeySizes(int selectedAlgorithim)
        {
            var keySizes   = new ObservableCollection <int>();
            var algortihim = (SymmetricMsdnCipher)selectedAlgorithim;
            var cipher     = SymmetricAlgorithm.Create(algortihim.ToString());

            foreach (var legalkeySize in cipher.LegalKeySizes)
            {
                int keySize = legalkeySize.MinSize;
                while (keySize <= legalkeySize.MaxSize)
                {
                    keySizes.Add(keySize);
                    if (legalkeySize.SkipSize == 0)
                    {
                        break;
                    }
                    keySize += legalkeySize.SkipSize;
                }
            }
            return(keySizes);
        }
        public void Init()
        {
            const string encryptionAlgorithm = "AES";
            const string hashAlgorithm       = "HMACSHA256";

            var shellSettings = new ShellSettings {
                Name                 = "Foo",
                DataProvider         = "Bar",
                DataConnectionString = "Quux",
                EncryptionAlgorithm  = encryptionAlgorithm,
                EncryptionKey        = SymmetricAlgorithm.Create(encryptionAlgorithm).Key.ToHexString(),
                HashAlgorithm        = hashAlgorithm,
                HashKey              = HMAC.Create(hashAlgorithm).Key.ToHexString()
            };

            var builder = new ContainerBuilder();

            builder.RegisterInstance(shellSettings);
            builder.RegisterType <DefaultEncryptionService>().As <IEncryptionService>();
            _container = builder.Build();
        }
Ejemplo n.º 30
0
        public void TestDataEncoding()
        {
            var key = SymmetricAlgorithm.Create("Rijndael");

            key.GenerateKey();
            key.GenerateIV();
            var fullkey = new byte[key.Key.Length + key.IV.Length];

            Array.Copy(key.Key, fullkey, key.Key.Length);
            Array.Copy(key.IV, 0, fullkey, key.Key.Length, key.IV.Length);

            var stringTest = "ewAiAGQAYQB0AGUAIgA6ACIAcwBhAGIAYQB0AG8AIAAyADAAIABmAGUAYgBiAHIAYQBpAG8AIAAyADAAMgAxACIALAAiAHQAZQB4AHQAIgA6ACIAZAAxAGQAYgBmADcAYgBhAC0AMwBhADUAZgAtADQANgBkAGEALQA4AGIAMQA5AC0ANQA5ADQAMgBjADMAMwA0ADEAMwA1ADYAIgAsACIAbQBlAHMAcwBhAGcAZQAiADoAIgBJACAAbABvAHYAZQAgAHkAbwB1ACIALAAiAF8AaABpAHMAdABvAHIAeQAiADoAWwBdAH0A";
            var data       = UnicodeEncoding.Unicode.GetBytes(stringTest);

            var service = new CryptoService();

            var encoded = service.EncodeData(data, fullkey);
            var decoded = service.DecodeData(encoded, fullkey);

            Assert.Equal(decoded, data);
        }