Esempio n. 1
0
        internal static byte[] TripleDESKeyWrapDecrypt(byte[] rgbKey, byte[] rgbEncryptedWrappedKeyData)
        {
            // Check to see whether the length of the encrypted key is reasonable
            if (rgbEncryptedWrappedKeyData.Length != 32 && rgbEncryptedWrappedKeyData.Length != 40 &&
                rgbEncryptedWrappedKeyData.Length != 48)
            {
                throw new CryptographicException(SR.Cryptography_Xml_KW_BadKeySize);
            }

            TripleDES        tripleDES = null;
            ICryptoTransform dec1      = null;
            ICryptoTransform dec2      = null;

            try
            {
                tripleDES = TripleDES.Create();
                // Assume no padding, use CBC mode
                tripleDES.Padding = PaddingMode.None;
                dec1 = tripleDES.CreateDecryptor(rgbKey, s_rgbTripleDES_KW_IV);

                byte[] temp2 = dec1.TransformFinalBlock(rgbEncryptedWrappedKeyData, 0, rgbEncryptedWrappedKeyData.Length);
                Array.Reverse(temp2);
                // Get the IV and temp1
                byte[] rgbIV = new byte[8];
                Buffer.BlockCopy(temp2, 0, rgbIV, 0, 8);
                byte[] temp1 = new byte[temp2.Length - rgbIV.Length];
                Buffer.BlockCopy(temp2, 8, temp1, 0, temp1.Length);

                dec2 = tripleDES.CreateDecryptor(rgbKey, rgbIV);
                byte[] rgbWKCKS = dec2.TransformFinalBlock(temp1, 0, temp1.Length);

                // checksum the key
                byte[] rgbWrappedKeyData = new byte[rgbWKCKS.Length - 8];
                Buffer.BlockCopy(rgbWKCKS, 0, rgbWrappedKeyData, 0, rgbWrappedKeyData.Length);
                using (var sha = SHA1.Create())
                {
                    byte[] rgbCKS = sha.ComputeHash(rgbWrappedKeyData);
                    for (int index = rgbWrappedKeyData.Length, index1 = 0; index < rgbWKCKS.Length; index++, index1++)
                    {
                        if (rgbWKCKS[index] != rgbCKS[index1])
                        {
                            throw new CryptographicException(SR.Cryptography_Xml_BadWrappedKeySize);
                        }
                    }
                    return(rgbWrappedKeyData);
                }
            }
            finally
            {
                dec2?.Dispose();
                dec1?.Dispose();
                tripleDES?.Dispose();
            }
        }
Esempio n. 2
0
        public string Decrypt(string data, int vi)
        {
            MemoryStream ms = new MemoryStream();

            Byte[] tb = Convert.FromBase64String(data);
            des.Key = Convert.FromBase64String(Keys[vi]);
            des.IV  = Convert.FromBase64String(IVs[vi]);
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(tb, 0, tb.Length);
            cs.Flush();
            cs.Close();
            return(Encoding.Unicode.GetString(ms.ToArray()));
        }
Esempio n. 3
0
        /// <summary>
        /// 三重DES解密
        /// </summary>
        /// <param name="cipherText"></param>
        /// <param name="secretKey">由淘宝提供的码商密钥</param>
        /// <returns></returns>
        public static string TripleDES_Decrypt(string cipherText, string secretKey)
        {
            if (string.IsNullOrWhiteSpace(cipherText))
            {
                return(cipherText);
            }
            string plaintext = cipherText;

            using (TripleDES desAlg = TripleDES.Create())
            {
                desAlg.Key = Encoding.UTF8.GetBytes(secretKey.Substring(0, 24));
                desAlg.IV  = Encoding.UTF8.GetBytes(secretKey.Substring(0, 8));
                ICryptoTransform decryptor   = desAlg.CreateDecryptor(desAlg.Key, desAlg.IV);
                byte[]           bCipherText = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bCipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return(plaintext);
        }
Esempio n. 4
0
        public static string ThreeDesDecryptHEX(string input)
        {
            TripleDES edes = TripleDES.Create();

            edes.Mode    = CipherMode.CBC;
            edes.Padding = PaddingMode.PKCS7;
            byte[] rgbKey = new byte[] {
                1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4,
                5, 6, 1, 2, 3, 4, 5, 6
            };
            byte[]           rgbIV     = new byte[] { 1, 2, 3, 4, 5, 6, 1, 2 };
            ICryptoTransform transform = edes.CreateDecryptor(rgbKey, rgbIV);

            if (input.Length <= 1)
            {
                throw new Exception("encrypted HEX string is too short!");
            }
            byte[] buffer = new byte[input.Length / 2];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = Convert.ToByte(input.Substring(i * 2, 2), 0x10);
            }
            MemoryStream stream  = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);

            stream2.Write(buffer, 0, buffer.Length);
            stream2.FlushFinalBlock();
            stream2.Close();
            return(Encoding.GetEncoding("GB2312").GetString(stream.ToArray()));
        }
        public static void MultipleBlockDecryptTransform(bool blockAlignedOutput)
        {
            const string ExpectedOutput = "This is a test";

            int outputPadding = blockAlignedOutput ? 0 : 3;

            byte[] key          = "0123456789ABCDEFFEDCBA9876543210ABCDEF0123456789".HexToByteArray();
            byte[] iv           = "0123456789ABCDEF".HexToByteArray();
            byte[] outputBytes  = new byte[iv.Length * 2 + outputPadding];
            byte[] input        = "A61C8F1D393202E1E3C71DCEAB9B08DB".HexToByteArray();
            int    outputOffset = 0;

            using (TripleDES alg = TripleDESFactory.Create())
                using (ICryptoTransform xform = alg.CreateDecryptor(key, iv))
                {
                    Assert.Equal(2 * alg.BlockSize, (outputBytes.Length - outputPadding) * 8);
                    outputOffset += xform.TransformBlock(input, 0, input.Length, outputBytes, outputOffset);
                    byte[] overflow = xform.TransformFinalBlock(Array.Empty <byte>(), 0, 0);
                    Buffer.BlockCopy(overflow, 0, outputBytes, outputOffset, overflow.Length);
                    outputOffset += overflow.Length;
                }

            string decrypted = Encoding.ASCII.GetString(outputBytes, 0, outputOffset);

            Assert.Equal(ExpectedOutput, decrypted);
        }
        public static void DecryptorReuse_LeadsToSameResults(CipherMode cipherMode, int feedbackSize)
        {
            // AppleCCCryptor does not allow calling Reset on CFB cipher.
            // this test validates that the behavior is taken into consideration.
            var input = "896072ab28e5fdfc9e8b3610627bf27a".HexToByteArray();
            var key   = "c179d0fdd073a1910e51f1d5fe70047ac179d0fdd073a191".HexToByteArray();
            var iv    = "b956d5426d02b247".HexToByteArray();

            using (TripleDES tdes = TripleDESFactory.Create())
            {
                tdes.Mode    = cipherMode;
                tdes.Key     = key;
                tdes.IV      = iv;
                tdes.Padding = PaddingMode.None;

                if (feedbackSize > 0)
                {
                    tdes.FeedbackSize = feedbackSize;
                }

                using (ICryptoTransform transform = tdes.CreateDecryptor())
                {
                    byte[] output1 = transform.TransformFinalBlock(input, 0, input.Length);
                    byte[] output2 = transform.TransformFinalBlock(input, 0, input.Length);

                    Assert.Equal(output1, output2);
                }
            }
        }
Esempio n. 7
0
        //public static DateTime ConvertToDate(string DateString)
        //{
        //    try
        //    {
        //        string[] arrDate = DateString.Split('/');
        //        return DateTime.Parse(string.Format("{2}/{1}/{0}", arrDate[0], arrDate[1], arrDate[2]));
        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
        //}


        #region Symmetric Cryptography (Triple DES)

        public static string SymmetricDecrypt(string input)
        {
#if DEBUG
            try
            {
#endif
            byte[] clearData;
            string result;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(System.Convert.FromBase64String(input), 0, System.Convert.FromBase64String(input).Length);
                    cs.FlushFinalBlock();
                    clearData = ms.ToArray();
                    ms.Close();
                    cs.Close();
                    result = Encoding.UTF8.GetString(clearData);
                }
            }

            return(result);

#if DEBUG
        }

        catch
        {
            return(input);
        }
#endif
        }
Esempio n. 8
0
    public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
    {
        try
        {
            // Create a new MemoryStream using the passed
            // array of encrypted data.
            MemoryStream msDecrypt = new MemoryStream(Data);

            // Create a new TripleDES object.
            TripleDES tripleDESalg = TripleDES.Create();

            // Create a CryptoStream using the MemoryStream
            // and the passed key and initialization vector (IV).
            CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                                                      tripleDESalg.CreateDecryptor(Key, IV),
                                                      CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] fromEncrypt = new byte[Data.Length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            //Convert the buffer into a string and return it.
            return(new ASCIIEncoding().GetString(fromEncrypt));
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return(null);
        }
    }
Esempio n. 9
0
        private byte[] desDecrypt(byte[] image, String pin)
        {
            //get hashed pincode to byte array
            byte[] keyBytes = Encoding.UTF8.GetBytes(pin);

            //make sure the keybytes are 24 bytes and copy the first 24 bytes
            byte[] newBytes = new byte[24];
            Array.Copy(keyBytes, 0, newBytes, 0, 24);

            //create new IV byte array
            byte[] IV = new byte[8];

            //Create C# TRiple DES algorithm
            TripleDES tdes = TripleDES.Create();

            //create the Triple DES parameters and the modes of Triple DES
            tdes.Key     = newBytes;
            tdes.Mode    = CipherMode.CBC;
            tdes.Padding = PaddingMode.PKCS7;
            tdes.IV      = IV;

            //create Decryptor
            var Encryptor = tdes.CreateDecryptor();

            //encrypt the image bytes
            byte[] outpur = Encryptor.TransformFinalBlock(image, 0, image.Length);
            tdes.Clear();

            return(outpur);
        }
Esempio n. 10
0
        /// <summary>
        /// Decrypts an encrypted stream of bytes by using a TripleDES symmetric algorithm.
        /// </summary>
        /// <param name="cipherValue">The encrypted stream of bytes to be decrypted.</param>
        /// <param name="key">Symmetric algorithm key.</param>
        /// <returns>A stream of bytes.</returns>
        private byte[] Decrypt(byte[] cipherValue, byte[] key)
        {
            byte[] plainValue = new byte[cipherValue.Length];

            TripleDES    algorithm = TripleDESCryptoServiceProvider.Create();
            MemoryStream memStream = new MemoryStream(cipherValue);

            CryptoStream cryptoStream = new CryptoStream(memStream, algorithm.CreateDecryptor(key, IV), CryptoStreamMode.Read);

            try
            {
                cryptoStream.Read(plainValue, 0, plainValue.Length);
            }
            catch (Exception e)
            {
                throw new UIPException(Resource.ResourceManager[Resource.Exceptions.RES_ExceptionSecureSqlProviderCantDecrypt] + UIPException.GetFirstExceptionMessage(e), e);
            }
            finally
            {
                //Flush the stream buffer
                cryptoStream.Close();
            }

            return(plainValue);
        }
Esempio n. 11
0
        /// <summary>
        /// DES decrypt
        /// </summary>
        /// <param name="data">Encrypted data</param>
        /// <param name="key">Key, requires 24 bits</param>
        /// <returns>Decrypted string</returns>
        public static string DESDecrypt(string data, string key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(data);
            Byte[] bKey           = new Byte[24];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);

            using (MemoryStream mStream = new MemoryStream(encryptedBytes))
                using (TripleDES des = TripleDES.Create())
                {
                    des.Mode    = CipherMode.ECB;
                    des.Padding = PaddingMode.PKCS7;
                    des.Key     = bKey;
                    using (CryptoStream cryptoStream = new CryptoStream(mStream, des.CreateDecryptor(), CryptoStreamMode.Read))
                        try
                        {
                            byte[] tmp = new byte[encryptedBytes.Length];
                            int    len = cryptoStream.Read(tmp, 0, encryptedBytes.Length);
                            byte[] ret = new byte[len];
                            Array.Copy(tmp, 0, ret, 0, len);
                            return(Encoding.UTF8.GetString(ret));
                        }
                        catch
                        {
                            return(null);
                        }
                }
        }
        internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            switch (this.algorithmID)
            {
            case EncryptionAlgorithm.Des:
                DES des = (DES) new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;
                des.Key  = bytesKey;
                des.IV   = this.initVec;
                return(des.CreateDecryptor());

            case EncryptionAlgorithm.Rc2:
                RC2 rc2 = (RC2) new RC2CryptoServiceProvider();
                rc2.Mode = CipherMode.CBC;
                return(rc2.CreateDecryptor(bytesKey, this.initVec));

            case EncryptionAlgorithm.Rijndael:
                Rijndael rijndael = (Rijndael) new RijndaelManaged();
                rijndael.Mode = CipherMode.CBC;
                return(rijndael.CreateDecryptor(bytesKey, this.initVec));

            case EncryptionAlgorithm.TripleDes:
                TripleDES tripleDes = (TripleDES) new TripleDESCryptoServiceProvider();
                tripleDes.Mode = CipherMode.CBC;
                return(tripleDes.CreateDecryptor(bytesKey, this.initVec));

            default:
                throw new CryptographicException("Algorithm ID '" + (object)this.algorithmID + "' not supported.");
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Decrypts an salted string
        /// </summary>
        /// <param name="encryptedString"></param>
        public string Decrypt(string encryptedString)
        {
            string returnValue;

            try
            {
                string itemToDecrypt = encryptedString;
                if (this.EncodeForURL)
                {
                    itemToDecrypt = Uri.UnescapeDataString(encryptedString).Replace("%20", "+");
                }
                using (TripleDES des = CreateDes())
                {
                    ICryptoTransform decryptor = des.CreateDecryptor();
                    var encryptedByte          = Convert.FromBase64String(itemToDecrypt);
                    var decryptedByte          = decryptor.TransformFinalBlock(encryptedByte, 0, encryptedByte.Length);
                    var decryptedSaltedString  = Encoding.Unicode.GetString(decryptedByte);
                    // Final decryption and return
                    returnValue = decryptedSaltedString.Remove(decryptedSaltedString.Length - this.Salt.Length);
                }
            }
            catch
            {
                returnValue = string.Empty;
            }

            return(returnValue);
        }
Esempio n. 14
0
        private byte[] DecryptPBDK2(byte[] edata, byte[] salt, byte[] IV, SecureString secpswd, int iterations)
        {
            CryptoStream stream = null;
            IntPtr       zero   = IntPtr.Zero;

            byte[] destination = new byte[secpswd.Length];
            zero = Marshal.SecureStringToGlobalAllocAnsi(secpswd);
            Marshal.Copy(zero, destination, 0, destination.Length);
            Marshal.ZeroFreeGlobalAllocAnsi(zero);
            try
            {
                Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(destination, salt, iterations);
                TripleDES          edes  = TripleDES.Create();
                edes.Key = bytes.GetBytes(0x18);
                edes.IV  = IV;
                MemoryStream stream2 = new MemoryStream();
                stream = new CryptoStream(stream2, edes.CreateDecryptor(), CryptoStreamMode.Write);
                stream.Write(edata, 0, edata.Length);
                stream.Flush();
                stream.Close();
                return(stream2.ToArray());
            }
            catch (Exception exception)
            {
                this.Mensaje = "Error al desencriptar la llave. " + exception.Message;
                return(null);
            }
        }
Esempio n. 15
0
        public override byte[] Transform(byte[] data, TransformType type)
        {
            MemoryStream     memoryStream = (MemoryStream)null;
            ICryptoTransform transform    = (ICryptoTransform)null;
            TripleDES        tripleDes    = TripleDES.Create();

            try
            {
                memoryStream  = new MemoryStream();
                tripleDes.Key = this.Key;
                tripleDes.IV  = this.IV;
                transform     = type != TransformType.ENCRYPT ? tripleDes.CreateDecryptor() : tripleDes.CreateEncryptor();
                if (data == null || data.Length == 0)
                {
                    return((byte[])null);
                }
                CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, transform, CryptoStreamMode.Write);
                cryptoStream.Write(data, 0, data.Length);
                cryptoStream.FlushFinalBlock();
                return(memoryStream.ToArray());
            }
            catch (CryptographicException ex)
            {
                throw new CryptographicException(ex.Message);
            }
            finally
            {
                tripleDes?.Clear();
                transform?.Dispose();
                memoryStream.Close();
            }
        }
Esempio n. 16
0
    public static string GetString(string _key)
    {
        // Hide '_key' string.
        byte[] hashData = md5HashMaker.ComputeHash(System.Text.Encoding.UTF8.GetBytes(_key));
        string hashKey  = System.Text.Encoding.UTF8.GetString(hashData);

        // Retrieve encrypted '_value' and Base64 decode it.
        string _value = PlayerPrefs.GetString(hashKey);

        if (string.IsNullOrEmpty(_value) == true)
        {
            return(string.Empty);
        }
        byte[] bytes = Convert.FromBase64String(_value);

        // Decrypt '_value' with 3DES.
        desMaker.Key  = md5HashMaker.ComputeHash(System.Text.Encoding.UTF8.GetBytes(privateKey));;
        desMaker.Mode = CipherMode.ECB;

        ICryptoTransform xform = desMaker.CreateDecryptor();

        byte[] decrypted = xform.TransformFinalBlock(bytes, 0, bytes.Length);

        // decrypte_value as a proper string.
        string decryptedString = System.Text.Encoding.UTF8.GetString(decrypted);

        //Debug.Log("GetString hashKey: " + hashKey + " GetData: " + _value + " Decrypted Data: " + decryptedString);
        return(decryptedString);
    }
        private void tripleDesDecryption(String cipher, String padding, String key)
        {
            using (TripleDES tDes = TripleDES.Create())
            {
                tDes.Mode    = (CipherMode)Enum.Parse(typeof(CipherMode), cipher, true);
                tDes.Padding = (PaddingMode)Enum.Parse(typeof(PaddingMode), padding, true);
                tDes.KeySize = 128;
                tDes.Key     = getBytes(this.KeyTextBox.Text);

                byte[] input  = File.ReadAllBytes(this.InputTextBox.Text);
                string output = null;

                ICryptoTransform decryptor = tDes.CreateDecryptor(tDes.Key, tDes.IV);

                using (MemoryStream msDecrypt = new MemoryStream(input))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            output = srDecrypt.ReadToEnd();
                        }
                    }
                }

                File.WriteAllText(this.OutputTextBox.Text, output);
                MessageBox.Show("Succesfuly decrypted!");
            }
        }
Esempio n. 18
0
        private string Decrypt7(byte[] Data, byte[] Key)
        {
            // Create a new MemoryStream using the passed
            // array of encrypted data.
            MemoryStream msDecrypt = new MemoryStream(Data);

            // Create a new TripleDES object.
            TripleDES tripleDESalg = TripleDES.Create();

            tripleDESalg.Key     = Key;
            tripleDESalg.Padding = PaddingMode.None;

            // Create a CryptoStream using the MemoryStream
            // and the passed key and initialization vector (IV).
            CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                                                      tripleDESalg.CreateDecryptor(), CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] fromEncrypt = new byte[Data.Length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            //Convert the buffer into a string and return it.
            return(UTF8Encoding.UTF8.GetString(fromEncrypt));
        }
Esempio n. 19
0
    public int DecryptUserId(string id, string password, string salt)
    {
        byte[]             saltBytes = new UTF8Encoding(false).GetBytes(salt);
        Rfc2898DeriveBytes key       = new Rfc2898DeriveBytes(password, saltBytes, USER_ID_HASH_ITERATIONS);

        TripleDES decryptor = TripleDES.Create();

        decryptor.Padding = PaddingMode.PKCS7;
        decryptor.Mode    = CipherMode.CBC;

        byte[] relevantBytes = key.GetBytes(KEY_HASH_BYTES);
        PrintBytes(relevantBytes);

        decryptor.Key = relevantBytes;
        decryptor.IV  = key.GetBytes(IV_HASH_BYTES);

        int result;

        using (MemoryStream mem = new MemoryStream())
        {
            using (CryptoStream crypt = new CryptoStream(mem, decryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                byte[] base64Data = Convert.FromBase64String(id);

                crypt.Write(base64Data, 0, base64Data.Length);
            }
            byte[] utf8Bytes = mem.ToArray();
            PrintBytes(utf8Bytes);

            result = int.Parse(new UTF8Encoding(false).GetString(utf8Bytes));
        }

        return(result);
    }
Esempio n. 20
0
        public static void TripleDesCreate()
        {
            byte[]    inputBytes = Encoding.ASCII.GetBytes("This is a secret message and is a sentence that is longer than a block, it ensures that multi-block functions work.");
            TripleDES tripleDes  = TripleDES.Create();

            byte[] encryptedBytes;
            using (MemoryStream input = new MemoryStream(inputBytes))
                using (CryptoStream cryptoStream = new CryptoStream(input, tripleDes.CreateEncryptor(), CryptoStreamMode.Read))
                    using (MemoryStream output = new MemoryStream())
                    {
                        cryptoStream.CopyTo(output);
                        encryptedBytes = output.ToArray();
                    }

            Assert.NotEqual(inputBytes, encryptedBytes);

            byte[] decryptedBytes;
            using (MemoryStream input = new MemoryStream(encryptedBytes))
                using (CryptoStream cryptoStream = new CryptoStream(input, tripleDes.CreateDecryptor(), CryptoStreamMode.Read))
                    using (MemoryStream output = new MemoryStream())
                    {
                        cryptoStream.CopyTo(output);
                        decryptedBytes = output.ToArray();
                    }

            Assert.Equal(inputBytes, decryptedBytes);
        }
Esempio n. 21
0
        /// <summary>
        /// Decrypts an salted string
        /// </summary>
        /// <param name="encryptedString"></param>
        public string Decrypt(string encryptedString)
        {
            var returnValue   = TypeExtension.DefaultString;
            var itemToDecrypt = TypeExtension.DefaultString;

            try
            {
                itemToDecrypt = encryptedString;
                if (this.EncodeForURL)
                {
                    itemToDecrypt = UrlEncoder.Decode(encryptedString);
                }
                TripleDES        des       = CreateDes();
                ICryptoTransform decryptor = des.CreateDecryptor();
                var encryptedByte          = Convert.FromBase64String(itemToDecrypt);
                var decryptedByte          = decryptor.TransformFinalBlock(encryptedByte, 0, encryptedByte.Length);
                var decryptedSaltedString  = Encoding.Unicode.GetString(decryptedByte);
                // Final decryption and return
                returnValue = decryptedSaltedString.Remove(decryptedSaltedString.Length - this.Salt.Length);
            }
            catch
            {
                returnValue = TypeExtension.DefaultString;
            }

            return(returnValue);
        }
Esempio n. 22
0
        /// <summary>
        /// ถอดรหัสด้วย TripleDEC
        /// </summary>
        /// <param name="keyHash">Key ที่ใช้ถอดรหัส</param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string SymmetricDecrypt(string keyHash, string input)
        {
            byte[] clearData;
            string result;

            using (MemoryStream ms = new MemoryStream())
            {
                using (TripleDES tripleDES = TripleDES.Create())
                {
                    tripleDES.Key  = Encoding.ASCII.GetBytes((keyHash + "!@#$%^&*()_+|").PadRight(24, '฿').Substring(0, 24));
                    tripleDES.Mode = CipherMode.ECB;

                    using (CryptoStream cs = new CryptoStream(ms, tripleDES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] byteInput = System.Convert.FromBase64String(input);
                        cs.Write(byteInput, 0, byteInput.Length);
                        cs.FlushFinalBlock();
                        clearData = ms.ToArray();

                        ms.Close();
                        cs.Close();
                        result = Encoding.ASCII.GetString(clearData);
                    }
                }
            }
            return(result);
        }
Esempio n. 23
0
 public byte[] Des3Decrypt(byte[] data, byte[] key, byte[] iv)
 {
     try
     {
         TripleDES edes = TripleDES.Create();
         if (iv != null)
         {
             edes.IV = iv;
         }
         edes.Key     = key;
         edes.Mode    = CipherMode.ECB;
         edes.Padding = PaddingMode.None;
         byte[] buffer = new byte[0];
         return(edes.CreateDecryptor().TransformFinalBlock(data, 0, data.Length));
     }
     catch (CryptographicException exception)
     {
         logger.ErrorFormat("A Cryptographic error occurred: {0}, Data={1}, Length={2}", new object[] { exception.Message, data.Length, data.Length });
         return(null);
     }
     catch (Exception exception2)
     {
         logger.ErrorFormat("A exception occurred: {0}", new object[] { exception2.Message });
         return(null);
     }
 }
        public static void TransformWithTooShortOutputBuffer(bool encrypt, bool blockAlignedOutput)
        {
            using (TripleDES alg = TripleDESFactory.Create())
                using (ICryptoTransform xform = encrypt ? alg.CreateEncryptor() : alg.CreateDecryptor())
                {
                    // 1 block, plus maybe three bytes
                    int    outputPadding = blockAlignedOutput ? 0 : 3;
                    byte[] output        = new byte[alg.BlockSize / 8 + outputPadding];
                    // 3 blocks of 0x00
                    byte[] input = new byte[3 * (alg.BlockSize / 8)];

                    Type exceptionType = typeof(ArgumentOutOfRangeException);

                    // TripleDESCryptoServiceProvider doesn't throw the ArgumentOutOfRangeException,
                    // giving a CryptographicException when CAPI reports the destination too small.
                    if (PlatformDetection.IsNetFramework)
                    {
                        exceptionType = typeof(CryptographicException);
                    }

                    Assert.Throws(
                        exceptionType,
                        () => xform.TransformBlock(input, 0, input.Length, output, 0));

                    Assert.Equal(new byte[output.Length], output);
                }
        }
Esempio n. 25
0
        static void Main()
        {
            Console.WriteLine("ENTER KEY");
            string    key = Console.ReadLine();
            TripleDES des = CreateDES(key);

            //encrypt
            Console.WriteLine("ENCRYPT (e) OR DECRYPT (d)?");
            string answer = Console.ReadLine();

            if (answer == "e")
            {
                Console.WriteLine("Type in your string");
                ICryptoTransform ct        = des.CreateEncryptor();
                byte[]           input     = utf8.GetBytes(Console.ReadLine());
                byte[]           encrypted = ct.TransformFinalBlock(input, 0, input.Length);
                Console.WriteLine(Convert.ToBase64String(encrypted));
            }
            //decrypt
            else if (answer == "d")
            {
                Console.WriteLine("Type in your string");
                string           CypherText = Console.ReadLine();
                byte[]           b          = Convert.FromBase64String(CypherText);
                ICryptoTransform ct         = des.CreateDecryptor();
                byte[]           input      = ct.TransformFinalBlock(b, 0, b.Length);
                string           decrypted  = utf8.GetString(input);
                Console.WriteLine(decrypted);
            }
            else
            {
                Console.WriteLine("GEEN OPTIE.");
            }
            Console.ReadLine();
        }
Esempio n. 26
0
        /// <summary>
        /// DES decrypt
        /// </summary>
        /// <param name="data">Encrypted data</param>
        /// <param name="key">Key, requires 24 bits</param>
        /// <returns>Decrypted byte array</returns>
        public static byte[] DESDecrypt(byte[] data, string key)
        {
            Check.Argument.IsNotEmpty(data, nameof(data));
            Check.Argument.IsNotEmpty(key, nameof(key));
            Check.Argument.IsNotOutOfRange(key.Length, 24, 24, nameof(key));

            Byte[] encryptedBytes = data;
            Byte[] bKey           = new Byte[24];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);

            using (MemoryStream Memory = new MemoryStream(encryptedBytes))
            {
                using (TripleDES des = TripleDES.Create())
                {
                    des.Mode    = CipherMode.ECB;
                    des.Padding = PaddingMode.PKCS7;
                    des.Key     = bKey;
                    using (CryptoStream cryptoStream = new CryptoStream(Memory, des.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        try
                        {
                            byte[] tmp = new byte[encryptedBytes.Length];
                            int    len = cryptoStream.Read(tmp, 0, encryptedBytes.Length);
                            byte[] ret = new byte[len];
                            Array.Copy(tmp, 0, ret, 0, len);
                            return(ret);
                        }
                        catch
                        {
                            return(null);
                        }
                    }
                }
            }
        }
Esempio n. 27
0
        public static byte[] DecryptPBDK2(
            byte[] edata,
            byte[] salt,
            byte[] IV,
            SecureString secpswd,
            int iterations)
        {
            IntPtr zero = IntPtr.Zero;

            byte[] numArray        = new byte[secpswd.Length];
            IntPtr globalAllocAnsi = Marshal.SecureStringToGlobalAllocAnsi(secpswd);

            Marshal.Copy(globalAllocAnsi, numArray, 0, numArray.Length);
            Marshal.ZeroFreeGlobalAllocAnsi(globalAllocAnsi);
            try
            {
                Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(numArray, salt, iterations);
                TripleDES          tripleDes          = TripleDES.Create();
                tripleDes.Key = rfc2898DeriveBytes.GetBytes(24);
                tripleDes.IV  = IV;
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, tripleDes.CreateDecryptor(), CryptoStreamMode.Write);
                cryptoStream.Write(edata, 0, edata.Length);
                cryptoStream.Flush();
                cryptoStream.Close();
                return(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Problem decrypting: {0}", (object)ex.Message);
                return((byte[])null);
            }
        }
        public static void InvalidCFBFeedbackSizes(int feedbackSize, bool discoverableInSetter)
        {
            using (TripleDES tdes = TripleDESFactory.Create())
            {
                tdes.GenerateKey();
                tdes.Mode = CipherMode.CFB;

                if (discoverableInSetter)
                {
                    // there are some key sizes that are invalid for any of the modes,
                    // so the exception is thrown in the setter
                    Assert.Throws <CryptographicException>(() =>
                    {
                        tdes.FeedbackSize = feedbackSize;
                    });
                }
                else
                {
                    tdes.FeedbackSize = feedbackSize;

                    // however, for CFB only few sizes are valid. Those should throw in the
                    // actual AES instantiation.

                    Assert.Throws <CryptographicException>(() => tdes.CreateDecryptor());
                    Assert.Throws <CryptographicException>(() => tdes.CreateEncryptor());
                }
            }
        }
Esempio n. 29
0
        //  ------  Uses PBKD2 to derive a 3DES key and decrypts data --------
        public static byte[] DecryptPBDK2(byte[] edata, byte[] salt, byte[] IV, SecureString secpswd, int iterations)
        {
            CryptoStream decrypt = null;

            IntPtr unmanagedPswd = IntPtr.Zero;

            byte[] psbytes = new byte[secpswd.Length];
            unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd);
            Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length);
            Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd);

            try
            {
                Rfc2898DeriveBytes kd     = new Rfc2898DeriveBytes(psbytes, salt, iterations);
                TripleDES          decAlg = TripleDES.Create();
                decAlg.Key = kd.GetBytes(24);
                decAlg.IV  = IV;
                MemoryStream memstr = new MemoryStream();
                decrypt = new CryptoStream(memstr, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
                decrypt.Write(edata, 0, edata.Length);
                decrypt.Flush();
                decrypt.Close();    // this is REQUIRED.
                byte[] cleartext = memstr.ToArray();
                return(cleartext);
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem decrypting: {0}", e.Message);
                return(null);
            }
        }
Esempio n. 30
0
        public static string desencriptaPHP(string _key24, string _iv, string _data)
        {
            byte[] key = Encoding.ASCII.GetBytes(_key24);

            byte[] iv = Encoding.ASCII.GetBytes(_iv);

            byte[] data = Convert.FromBase64String(_data);

            byte[] enc = new byte[0];

            TripleDES tdes = TripleDES.Create();



            tdes.Mode = CipherMode.CBC;

            tdes.Padding = PaddingMode.Zeros;

            tdes.IV = iv;

            tdes.Key = key;



            ICryptoTransform ict = tdes.CreateDecryptor();

            enc = ict.TransformFinalBlock(data, 0, data.Length);

            string retorno = Encoding.ASCII.GetString(enc);

            retorno = retorno.Replace("\0", "");

            return(retorno);
        }
	// Check a TripleDES instance against a particular key and plaintext.
	// We do this by comparing against what DES would do, if applied manually.
	// This assumes that DES has already been tested and found to be OK.
	private static void CheckTripleDES(TripleDES alg, byte[] key,
									   byte[] plaintext)
			{
				// Set up the algorithm the way we want.
				alg.Mode = CipherMode.ECB;
				alg.Padding = PaddingMode.None;

				// Create an encryptor and determine the output ciphertext.
				ICryptoTransform encryptor = alg.CreateEncryptor(key, null);
				byte[] ciphertext = new byte [plaintext.Length * 2];
				byte[] tail;
				int len = encryptor.TransformBlock
						(plaintext, 0, plaintext.Length,
						 ciphertext, 0);
				AssertEquals("ECB encrypt length mismatch",
							 len, plaintext.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);

				// Create a decryptor and run the test backwards.
				ICryptoTransform decryptor = alg.CreateDecryptor(key, null);
				byte[] original = new byte [plaintext.Length * 2];
				len = decryptor.TransformBlock
						(ciphertext, 0, plaintext.Length, original, 0);
				AssertEquals("ECB decrypt length mismatch",
							 len, plaintext.Length);
				tail = decryptor.TransformFinalBlock
						(ciphertext, 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, original, 0,
								   plaintext.Length))
				{
					Fail("did not decrypt to the original plaintext");
				}

				// Now see what DES would say on the same input to make
				// sure that TripleDES is giving the correct behaviour.
				DES des = DES.Create();
				des.Mode = CipherMode.ECB;
				des.Padding = PaddingMode.None;
				ICryptoTransform encrypt1;
				ICryptoTransform decrypt2;
				ICryptoTransform encrypt3;
				if(key.Length == 16)
				{
					encrypt1 = des.CreateEncryptor(SubKey(key, 0, 8), null);
					decrypt2 = des.CreateDecryptor(SubKey(key, 8, 8), null);
					encrypt3 = des.CreateEncryptor(SubKey(key, 0, 8), null);
				}
				else
				{
					encrypt1 = des.CreateEncryptor(SubKey(key, 0, 8), null);
					decrypt2 = des.CreateDecryptor(SubKey(key, 8, 8), null);
					encrypt3 = des.CreateEncryptor(SubKey(key, 16, 8), null);
				}
				byte[] block = new byte [plaintext.Length];
				encrypt1.TransformBlock
						(plaintext, 0, plaintext.Length, block, 0);
				tail = encrypt1.TransformFinalBlock
						(plaintext, 0, 0);
				decrypt2.TransformBlock
						(block, 0, plaintext.Length, block, 0);
				tail = decrypt2.TransformFinalBlock
						(block, 0, 0);
				encrypt3.TransformBlock
						(block, 0, plaintext.Length, block, 0);
				tail = encrypt3.TransformFinalBlock
						(block, 0, 0);
				if(!IdenticalBlock(ciphertext, 0, block, 0, plaintext.Length))
				{
					Fail("TripleDES does not have the correct behaviour");
				}
			}