Esempio n. 1
0
        public static Stream get(Stream pIn)
        {
            Rijndael     rij  = null;
            Rijndael     rij3 = null;
            CryptoStream cs   = null;



            try
            {
                rij  = Rijndael.Create();
                rij3 = Rijndael.Create();
                byte[] b;
                b = new byte[ChainConst.SystemV.Length];
                for (int i = 0; i < b.Length; ++i)
                {
                    b[i] = (byte)(ChainConst.SystemV[i] + 3);
                }
                rij.IV = ChainConst.SystemV;
                b      = new byte[ChainConst.SystemK.Length];
                for (int i = 0; i < b.Length; ++i)
                {
                    b[i] = (byte)(ChainConst.SystemK[i] + 3);
                }
                rij.Key = ChainConst.SystemK;

                pIn.Read(ChainConst.tempbuf, 0, ChainConst.tempbuf.Length);
                pIn.Read(ChainConst.tempbuf, 0, ChainConst.tempbuf.Length);
                pIn.Read(ChainConst.tempbuf, 0, ChainConst.tempbuf.Length);

                rij3.IV  = new byte[ChainConst.SystemV.Length];
                rij3.Key = new byte[ChainConst.SystemK.Length];

                b = new byte[ChainConst.SystemV.Length];
                pIn.Read(b, 0, b.Length);
                rij3.IV = b;
                b       = new byte[ChainConst.SystemK.Length];
                pIn.Read(b, 0, b.Length);
                rij3.Key = b;

                int count = pIn.ReadByte();
                count = (count % 13) + 1;
                for (int i = 0; i < count; ++i)
                {
                    pIn.Read(ChainConst.tempbuf, 0, ChainConst.tempbuf.Length);
                }



                cs = new CryptoStream(pIn, rij.CreateDecryptor(), CryptoStreamMode.Read);
                cs = new CryptoStream(cs, rij.CreateDecryptor(), CryptoStreamMode.Read);
                cs = new CryptoStream(cs, rij3.CreateDecryptor(), CryptoStreamMode.Read);
                cs = new CryptoStream(cs, rij.CreateDecryptor(), CryptoStreamMode.Read);



                return(cs);
            }
            catch //(Exception exc)
            {
                return(null);
            }
        }
Esempio n. 2
0
 public Aes(Rijndael rijObject)
 {
     _rijObject = rijObject;
     _encryptor = _rijObject.CreateEncryptor();
     _decryptor = _rijObject.CreateDecryptor();
 }
Esempio n. 3
0
        public static bool Decrypt(string FileName, string outFileName, string secret)
        {
            try
            {
                using (FileStream fileOutStream = File.Create(outFileName))
                    using (Rijndael rijndael = GetRijndael(secret))
                        using (FileStream fileStream = File.OpenRead(FileName))
                            using (CryptoStream cryptoStream = new CryptoStream(fileOutStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write, true))
                            {
                                fileStream.CopyTo(cryptoStream);
                            }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Esempio n. 4
0
 /// <summary>  
 /// 解密  参数:byte[] 
 /// </summary>  
 /// <param name="encryptedData">被解密的密文</param>  
 /// <param name="key">密钥</param>  
 /// <param name="iv">向量</param>  
 /// <returns>明文</returns>  
 public byte[] Decrypt(byte[] encryptedData, string key, string iv, EncodingStrOrByte.EncodingType encodingType = EncodingStrOrByte.EncodingType.UTF8)
 {
     if (encryptedData == null)
     {
         return(null);
     }
     if (!(CheckKey(key) && CheckIv(iv)))
     {
         return(encryptedData);
     }
     byte[] bKey = new byte[32];
     Array.Copy(EncodingStrOrByte.GetBytes(key.PadRight(bKey.Length), encodingType), bKey, bKey.Length);
     byte[] bVector = new byte[16];
     Array.Copy(EncodingStrOrByte.GetBytes(iv.PadRight(bVector.Length), encodingType), bVector, bVector.Length);
     byte[] original          = null; // 解密后的明文  
                 Rijndael Aes = Rijndael.Create();
                                      // 开辟一块内存流,存储密文  
                 using (MemoryStream Memory = new MemoryStream(encryptedData))
     {
                         // 把内存流对象包装成加密流对象  
                         using (CryptoStream Decryptor = new CryptoStream(Memory, Aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read))
         {
                                 // 明文存储区  
                                 using (MemoryStream originalMemory = new MemoryStream())
             {
                 byte[] Buffer    = new byte[1024];
                 int    readBytes = 0;
                 while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
                 {
                     originalMemory.Write(Buffer, 0, readBytes);
                 }
                 original = originalMemory.ToArray();
             }
         }
     }
     return(original);
 }
Esempio n. 5
0
        // Decrypt a file into another file using a password

        public static void Decrypt(string fileIn,
                                   string fileOut, string Password)
        {
            // First we are going to open the file streams

            FileStream fsIn = new FileStream(fileIn,
                                             FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut,
                                              FileMode.OpenOrCreate, FileAccess.Write);

            // Then we are going to derive a Key and an IV from

            // the Password and create an algorithm

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                                                              new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                                                                           0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            Rijndael alg = Rijndael.Create();

            alg.Key = pdb.GetBytes(32);
            alg.IV  = pdb.GetBytes(16);

            // Now create a crypto stream through which we are going

            // to be pumping data.

            // Our fileOut is going to be receiving the Decrypted bytes.

            CryptoStream cs = new CryptoStream(fsOut,
                                               alg.CreateDecryptor(), CryptoStreamMode.Write);

            // Now will will initialize a buffer and will be

            // processing the input file in chunks.

            // This is done to avoid reading the whole file (which can be

            // huge) into memory.

            int bufferLen = 4096;

            byte[] buffer = new byte[bufferLen];
            int    bytesRead;

            do
            {
                // read a chunk of data from the input file

                bytesRead = fsIn.Read(buffer, 0, bufferLen);

                // Decrypt it

                cs.Write(buffer, 0, bytesRead);
            } while(bytesRead != 0);

            // close everything

            cs.Close(); // this will also close the unrelying fsOut stream

            fsIn.Close();
        }
Esempio n. 6
0
        public static void Decrypt(int i_length, string fileIn, string fileOut, string Password)
        {
            FileStream   fileStream   = null;
            FileStream   fileStream2  = null;
            CryptoStream cryptoStream = null;

            try
            {
                fileStream  = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
                fileStream2 = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
                PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(Password, new byte[]
                {
                    73,
                    118,
                    97,
                    110,
                    32,
                    77,
                    101,
                    100,
                    118,
                    101,
                    100,
                    101,
                    118
                });
                Rijndael rijndael = Rijndael.Create();
                rijndael.Key = passwordDeriveBytes.GetBytes(32);
                rijndael.IV  = passwordDeriveBytes.GetBytes(16);
                cryptoStream = new CryptoStream(fileStream2, rijndael.CreateDecryptor(), CryptoStreamMode.Write);
                byte[] buffer  = new byte[i_length * 1024];
                int    num     = 4096;
                byte[] buffer2 = new byte[num];
                int    num2    = fileStream.Read(buffer, 0, i_length * 1024);
                do
                {
                    int    num3  = AccessDBUpdate.GetPercent(fileStream.Position, fileStream.Length);
                    double value = 0.01 * (double)num3 * 40.0;
                    num3 = Convert.ToInt32(value);
                    if (num3 > 40)
                    {
                        num3 = 40;
                    }
                    if (num3 < 1)
                    {
                        num3 = 1;
                    }
                    DBTools.ProgramBar_Percent = num3;
                    num2 = fileStream.Read(buffer2, 0, num);
                    cryptoStream.Write(buffer2, 0, num2);
                }while (num2 != 0);
                cryptoStream.Close();
                fileStream.Close();
                DBTools.ProgramBar_Percent = 40;
            }
            catch (Exception ex)
            {
                try
                {
                    if (cryptoStream != null)
                    {
                        cryptoStream.Close();
                    }
                }
                catch
                {
                }
                try
                {
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                }
                catch
                {
                }
                try
                {
                    if (fileStream2 != null)
                    {
                        fileStream2.Close();
                    }
                }
                catch
                {
                }
                throw ex;
            }
        }
Esempio n. 7
0
        public bool UpdatePassword(byte[] userID, string password, string newPassword, string pepper)
        {
            if (userID == null)
            {
                throw new ArgumentNullException("userID");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (newPassword == null)
            {
                throw new ArgumentNullException("newPassword");
            }
            if (pepper == null)
            {
                throw new ArgumentNullException("pepper");
            }
            byte[] privateKeyRaw = userKeys.Get(userID);

            {            //verify password
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(privateKeyRaw);
                Stream        cryptoStream          = CreateCryptoStream(memoryStream, userID, password, pepper, CryptoStreamMode.Read);
                RSAParameters privateKey            = DeserializeKey(cryptoStream);
                RSAParameters pubKey = GetPublicKey(userID);
                if ((ByteSequenceComparer.Shared.Compare(pubKey.Modulus, privateKey.Modulus) != 0) || (ByteSequenceComparer.Shared.Compare(pubKey.Exponent, privateKey.Exponent) != 0))
                {
                    return(false);
                }
            }

            MemoryStream newKeyStream = new MemoryStream();
            Rijndael     oldPassRij   = CreateRijndael(userID, password, pepper);
            Rijndael     newPassRij   = CreateRijndael(userID, newPassword, pepper);

            System.Security.Cryptography.CryptoStream streamI = new CryptoStream(new System.IO.MemoryStream(privateKeyRaw), oldPassRij.CreateDecryptor(), CryptoStreamMode.Read);
            System.Security.Cryptography.CryptoStream streamO = new CryptoStream(newKeyStream, newPassRij.CreateEncryptor(), CryptoStreamMode.Write);
            var buffer = new byte[1024];
            var read   = streamI.Read(buffer, 0, buffer.Length);

            while (read > 0)
            {
                streamO.Write(buffer, 0, read);
                read = streamI.Read(buffer, 0, buffer.Length);
            }
            streamO.FlushFinalBlock();

            byte[] newKeyRaw = newKeyStream.ToArray();
            userKeys.Put(userID, newKeyRaw);
            return(true);
        }
Esempio n. 8
0
    private static byte[] smethod_7(byte[] byte_4)
    {
        MemoryStream memoryStream = new MemoryStream();
        Rijndael     rijndael     = Rijndael.Create();

        rijndael.Key = new byte[]
        {
            173,
            252,
            249,
            34,
            206,
            132,
            37,
            109,
            113,
            148,
            24,
            40,
            128,
            101,
            148,
            26,
            50,
            53,
            56,
            156,
            220,
            29,
            181,
            38,
            18,
            105,
            32,
            76,
            23,
            54,
            177,
            3
        };
        rijndael.IV = new byte[]
        {
            47,
            50,
            96,
            233,
            111,
            135,
            254,
            42,
            193,
            86,
            233,
            212,
            46,
            97,
            105,
            63
        };
        CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);

        cryptoStream.Write(byte_4, 0, byte_4.Length);
        cryptoStream.Close();
        return(memoryStream.ToArray());
    }
Esempio n. 9
0
        private void ImportData()
        {
            string m_sMasterImportFileName = DateTime.Now.ToString("dd-MMM-yyyy") + "_" + currentBranch.CompBrn_Name;

            openFileDialog1.FileName         = m_sMasterImportFileName;
            openFileDialog1.InitialDirectory = @"H:\";
            openFileDialog1.Filter           = "Master File (*.mstrexp)|*.mstrexp";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                m_sMasterImportFileName = openFileDialog1.FileName;

                if (File.Exists(m_sMasterImportFileName))
                {
                    IFormatter formatter = new BinaryFormatter();
                    using (Stream stream = new FileStream(m_sMasterImportFileName, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        byte[]       baKey        = { 51, 208, 75, 59, 223, 134, 241, 155, 170, 229, 177, 160, 246, 71, 77, 141, 66, 7, 223, 103, 97, 80, 235, 82, 94, 107, 226, 190, 76, 94, 31, 43 };
                        byte[]       baIV         = { 142, 96, 41, 14, 206, 132, 173, 19, 12, 50, 124, 121, 42, 27, 35, 9 };
                        Rijndael     rijndael     = Rijndael.Create();
                        CryptoStream cryptoStream = new CryptoStream(stream, rijndael.CreateDecryptor(baKey, baIV), CryptoStreamMode.Read);
                        //

                        {
                            CResult       oResult;
                            StringBuilder oErrBuilder = new StringBuilder();
                            try{
                                // UOM
                                ArrayList oListUOM = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Item Type
                                ArrayList oListItemType = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Item Group
                                ArrayList oListItemGroup = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Item
                                ArrayList oListItem = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Reorder Level
                                ArrayList oListReorderLevel = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Currency
                                List <CCurrency> oListCurrency = (List <CCurrency>)formatter.Deserialize(cryptoStream);

                                // Price Master
                                ArrayList oListPriceMaster = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Customer
                                ArrayList oListCustomer = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Supplier
                                ArrayList oListSupplier = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Company
                                List <CCompany> oListCompany = (List <CCompany>)formatter.Deserialize(cryptoStream);

                                // Company Branch
                                List <CCompanyBranch> oListCompanyBranch = (List <CCompanyBranch>)formatter.Deserialize(cryptoStream);

                                // Company Vs CompanyBranch
                                ArrayList oListCVB = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Inventory Location
                                ArrayList oListLocation = (ArrayList)formatter.Deserialize(cryptoStream);

                                // CompanyBranch Vs Location
                                ArrayList oListBVL = (ArrayList)formatter.Deserialize(cryptoStream);

                                // Employee
                                ArrayList oListEmployee = (ArrayList)formatter.Deserialize(cryptoStream);

                                // User
                                ArrayList oListUser = (ArrayList)formatter.Deserialize(cryptoStream);



                                //Import UOM
                                oResult = new CResult();
                                CUOMBO oUOMBO = new CUOMBO();
                                foreach (CUOM oUOM in oListUOM)
                                {
                                    oResult = oUOMBO.Import(oUOM);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("UOM : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                //Import Itemtyps
                                oResult = new CResult();
                                CItemBO oItemBO = new CItemBO();
                                foreach (CItemType oItemType in oListItemType)
                                {
                                    oResult = oItemBO.Import(oItemType);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Item Type : " + oResult.ErrMsg + "\n");
                                    }
                                }

                                //Item Group
                                oResult = new CResult();
                                foreach (CItemGroup oItemGroup in oListItemGroup)
                                {
                                    oResult = oItemBO.Import(oItemGroup);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Item Type : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import Item with images
                                oResult = new CResult();
                                foreach (CItem oItem in oListItem)
                                {
                                    oResult = oItemBO.Import(oItem);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Item : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Reorder Level
                                oResult = new CResult();
                                CReorderLevelBO oReorderLevelBO = new CReorderLevelBO();
                                foreach (CReorderLevel oReorderLevel in oListReorderLevel)
                                {
                                    oResult = oReorderLevelBO.Import(oReorderLevel);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("ReorderLevel : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // IMPORT CURRENCY
                                oResult = new CResult();
                                CCurrencyBO oCurrencyBO = new CCurrencyBO();
                                foreach (CCurrency oCurrency in oListCurrency)
                                {
                                    oResult = oCurrencyBO.Import(oCurrency);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Currency : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import Pricemaster
                                oResult = new CResult();
                                CPriceMasterBO oPriceMasterBO = new CPriceMasterBO();
                                foreach (CPriceMaster oPriceMaster in oListPriceMaster)
                                {
                                    oResult = oPriceMasterBO.Import(oPriceMaster);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Price : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import Customer
                                oResult = new CResult();
                                CCustomerBO oCustomerBO = new CCustomerBO();
                                foreach (CCustomer oCustomer in oListCustomer)
                                {
                                    oResult = oCustomerBO.Import(oCustomer);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Customer : " + oResult.ErrMsg + "/n");
                                    }
                                }


                                // Import supplier
                                oResult = new CResult();
                                CSupplierBO oSupplierBO = new CSupplierBO();
                                foreach (CSupplier oSupplier in oListSupplier)
                                {
                                    oResult = oSupplierBO.Import(oSupplier);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Supplier : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import company
                                oResult = new CResult();
                                CCompanyBO oCompanyBO = new CCompanyBO();

                                foreach (CCompany oCompany in oListCompany)
                                {
                                    oResult = oCompanyBO.Import(oCompany);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Company : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import company branch
                                oResult = new CResult();
                                CCompanyBranchBO oCompanyBranchBO = new CCompanyBranchBO();
                                foreach (CCompanyBranch oCompanyBranch in oListCompanyBranch)
                                {
                                    oResult = oCompanyBranchBO.Import(oCompanyBranch);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Company Branch: " + oResult.ErrMsg + "/n");
                                    }
                                }

                                //Company Vs CompanyBranch
                                oResult = new CResult();
                                CCVBBO oCVBBO = new CCVBBO();
                                foreach (CCVB oCVB in oListCVB)
                                {
                                    oResult = oCVBBO.Import(oCVB);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Company Vs CompanyBranch : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import Location
                                oResult = new CResult();
                                CLocBO oLocBO = new CLocBO();
                                foreach (CLocation oLocation in oListLocation)
                                {
                                    oResult = oLocBO.Import(oLocation);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Inventory location: " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import CompanyBranch Vs Location
                                oResult = new CResult();
                                foreach (CCVB oCVB in oListBVL)
                                {
                                    oResult = oCVBBO.ImportBVL(oCVB);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("CompanyBranch Vs Location : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import Employee
                                oResult = new CResult();
                                CEmployeeBO oEmployeeBO = new CEmployeeBO();
                                foreach (CEmployee oEmployee in oListEmployee)
                                {
                                    oResult = oEmployeeBO.Import(oEmployee);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("Employee : " + oResult.ErrMsg + "/n");
                                    }
                                }

                                // Import User
                                oResult = new CResult();
                                CUserBO oUserBO = new CUserBO();
                                foreach (CUser oUser in oListUser)
                                {
                                    oResult = oUserBO.Import(oUser);
                                    if (!oResult.IsSuccess)
                                    {
                                        oErrBuilder.Append("User : "******"/n");
                                    }
                                }

                                if (oErrBuilder.Length != 0)
                                {
                                    MessageBox.Show(oErrBuilder.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                else
                                {
                                    MessageBox.Show("Successfully Imported. ", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }

                            //
                            cryptoStream.Close();
                        }
                    }
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// 암호 데이터 문자열을 주어진 암호로 암호화 / 복호화
        /// </summary>
        /// <param name="cryptData">data to crypt</param>
        /// <param name="offset">offset of cryptData for crypt</param>
        /// <param name="count">length for crypt</param>
        /// <param name="cryptPwd">password string</param>
        /// <param name="keySalt">salt string</param>
        /// <param name="cryptType">crypt type</param>
        /// <returns>encrypted/decrypted data</returns>
        /// <remarks>if keySalt is null, then default keySalt is used</remarks>
        public static byte[] GetCrypt(byte[] cryptData, int offset, int count, string cryptPwd, byte[] keySalt, CryptType cryptType)
        {
            if (keySalt == null)
            {
                keySalt = new byte[] { 0x54, 0x81, 0x45, 0x4A, 0x3B, 0x5E, 0x52, 0x15, 0x86, 0x5A, 0x40, 0x3B, 0xB4 }
            }
            ;
            PasswordDeriveBytes pwdBytes = new PasswordDeriveBytes(cryptPwd, keySalt);

            Rijndael crypAlg = Rijndael.Create();

            crypAlg.Key = pwdBytes.GetBytes(32);
            crypAlg.IV  = pwdBytes.GetBytes(16);

            try
            {
                ICryptoTransform cryptoTranform = (cryptType == CryptType.Encrypt) ? crypAlg.CreateEncryptor() : crypAlg.CreateDecryptor();

                MemoryStream memStream = new MemoryStream();
                using (CryptoStream cryptStream = new CryptoStream(memStream, cryptoTranform, CryptoStreamMode.Write))
                {
                    cryptStream.Write(cryptData, offset, count);
                    cryptStream.FlushFinalBlock();
                    return(memStream.ToArray());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + " >" + ex.StackTrace);
            }
            return(null);
        }
    }
Esempio n. 11
0
        public string GetFilePathSync(string path)
        {
            var documentsPath = DocumentConstants.DocumentsPath;
            var pathToFile    = Path.Combine(documentsPath, "" + Waardes.Instance.GeselecteerdeBox, path.Substring(1, path.Length - 1));

            EmptyDecryptedFolder();


            if (!File.Exists(pathToFile))            //Does not exist
            {
                var explorer  = new RemoteExplorer();
                var fileBytes = explorer.GetFile(path);

                if (fileBytes == null)
                {
                    return(null);
                }

                if (!Directory.Exists(pathToFile.Substring(0, pathToFile.LastIndexOf("/"))))
                {
                    Directory.CreateDirectory(pathToFile.Substring(0, pathToFile.LastIndexOf("/")));
                }

                if (pathToFile != null)
                {
                    File.WriteAllBytes(pathToFile, fileBytes);
                }
            }



            // moeten buiten de root zitten
            if (path.Count(e => e == '/') > 1)
            {
                int index      = path.IndexOf('/', path.IndexOf('/') + 1);
                var rootFolder = path.Substring(0, index);
                var folder     = GetFolder(rootFolder).Result;

                if (folder.HasCryptoKeys)
                {
                    try{
                        Rijndael rijndael = Rijndael.Create();
                        rijndael.Key = folder.Key;
                        rijndael.IV  = folder.IV;

                        var decpath = Path.Combine(documentsPath, "decrypted", path.Substring(1, path.Length - 1));
                        if (!Directory.Exists(decpath.Substring(0, decpath.LastIndexOf("/"))))
                        {
                            Directory.CreateDirectory(decpath.Substring(0, decpath.LastIndexOf("/")));
                        }

                        using (var stream = new CryptoStream(File.OpenRead(pathToFile), rijndael.CreateDecryptor(), CryptoStreamMode.Read))
                            using (var fs = File.OpenWrite(decpath))
                            {
                                stream.CopyTo(fs);
                            }
                        return(decpath);
                    }catch (Exception ex) {
                        Insights.Report(ex);
                        return(pathToFile);
                    }
                }
            }

            return(pathToFile);
        }
Esempio n. 12
0
        public static void AppendStringToFile(string fileName, string plainText, byte[] key, byte[] iv)
        {
            using (Rijndael algo = Rijndael.Create())
            {
                algo.Key = key;
                // The IV is set below
                algo.Mode    = CipherMode.CBC;
                algo.Padding = PaddingMode.PKCS7;

                // Create the streams used for encryption.
                using (FileStream file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    byte[] previous       = null;
                    int    previousLength = 0;

                    long length = file.Length;

                    // No check is done that the file is correct!
                    if (length != 0)
                    {
                        // The IV length is equal to the block length
                        byte[] block = new byte[iv.Length];

                        if (length >= iv.Length * 2)
                        {
                            // At least 2 blocks, take the penultimate block
                            // as the IV
                            file.Position = length - iv.Length * 2;
                            file.Read(block, 0, block.Length);
                            algo.IV = block;
                        }
                        else
                        {
                            // A single block present, use the IV given
                            file.Position = length - iv.Length;
                            algo.IV       = iv;
                        }

                        // Read the last block
                        file.Read(block, 0, block.Length);

                        // And reposition at the beginning of the last block
                        file.Position = length - iv.Length;

                        // We use a MemoryStream because the CryptoStream
                        // will close the Stream at the end
                        using (var ms = new MemoryStream(block))
                            // Create a decrytor to perform the stream transform.
                            using (ICryptoTransform decryptor = algo.CreateDecryptor())
                                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                                {
                                    // Read all data from the stream. The decrypted last
                                    // block can be long up to block length characters
                                    // (so up to iv.Length) (this with AES + CBC)
                                    previous       = new byte[iv.Length];
                                    previousLength = cs.Read(previous, 0, previous.Length);
                                }
                    }
                    else
                    {
                        // Use the IV given
                        algo.IV = iv;
                    }

                    // Create an encryptor to perform the stream transform.
                    using (ICryptoTransform encryptor = algo.CreateEncryptor())
                        using (CryptoStream cs = new CryptoStream(file, encryptor, CryptoStreamMode.Write))
                            using (StreamWriter sw = new StreamWriter(cs))
                            {
                                // Rewrite the last block, if present. We even skip
                                // the case of block present but empty
                                if (previousLength != 0)
                                {
                                    cs.Write(previous, 0, previousLength);
                                }

                                // Write all data to the stream.
                                sw.Write(plainText);
                            }
                }
            }
        }
Esempio n. 13
0
        public static string Decrypt(string cipherText, string KEY)
        {
            if (KEY.Length > 32)
            {
                KEY = KEY.Substring(0, 32);
            }
            else if (KEY.Length < 32)
            {
                for (int i = 0; i < 32 - KEY.Length; i++)
                {
                    KEY = KEY + "X";
                }
            }
            byte[] KEY_BYTES = Encoding.UTF8.GetBytes(KEY);

            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new System.ArgumentNullException("cipherText");
            }

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an AesManaged object
            // with the specified key and IV.
            using (Rijndael algorithm = Rijndael.Create())
            {
                algorithm.Key = KEY_BYTES;

                // Get bytes from input string
                byte[] cipherBytes = new byte[0];
                try { cipherBytes = System.Convert.FromBase64String(cipherText); } catch { return(plaintext); }

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
                {
                    // Read IV first
                    byte[] IV = new byte[16];
                    msDecrypt.Read(IV, 0, IV.Length);

                    // Assign IV to an algorithm
                    algorithm.IV = IV;

                    // Create a decrytor to perform the stream transform.
                    var decryptor = algorithm.CreateDecryptor(algorithm.Key, algorithm.IV);

                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (var srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return(plaintext);
        }
Esempio n. 14
0
        private static byte[] AESDecryptorMain(byte[] value)
        {
            try
            {
                // Setup decrytion algorithm
                byte[] salt = new byte[8];
                for (int i = 0; i < salt.Length; i++)
                {
                    salt[i] = value[i];
                }
                Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(secretKey, salt);
                Rijndael           aes          = Rijndael.Create();
                aes.IV  = keyGenerator.GetBytes(aes.BlockSize / 8);
                aes.Key = keyGenerator.GetBytes(aes.KeySize / 8);

                // Decrypt data
                using (MemoryStream memoryStream = new MemoryStream())
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(value, 8, value.Length - 8);
                        cryptoStream.Close();
                        byte[] decrypted = memoryStream.ToArray();
                        return(decrypted);
                    }
            }
            catch (CryptographicException ex)
            {
                log.Write("AESDecryptorMain", ex.ToString(), System.Diagnostics.TraceEventType.Error);
                byte[] salt = new byte[1];
                for (int i = 0; i < salt.Length; i++)
                {
                    salt[i] = 0;
                }
                return(salt);
            }
        }
Esempio n. 15
0
        public static string Decrypt(string data, string password)
        {
            if (String.IsNullOrEmpty(data))
            {
                return(null);
            }
            if (String.IsNullOrEmpty(password))
            {
                return(null);
            }
            byte[] rawData = Encoding.Unicode.GetBytes(data);
            if (rawData.Length < 8)
            {
                throw new ArgumentException("Invalid input data");
            }
            // setup the decryption algorithm
            byte[] salt = new byte[8];
            for (int i = 0; i < salt.Length; i++)
            {
                salt[i] = rawData[i];
            }
            Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);
            Rijndael           aes          = Rijndael.Create();

            aes.IV  = keyGenerator.GetBytes(aes.BlockSize / 8);
            aes.Key = keyGenerator.GetBytes(aes.KeySize / 8);
            // decrypt the data
            using (MemoryStream memoryStream = new MemoryStream())
                try
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(rawData, 8, rawData.Length - 8);
                        cryptoStream.Close();
                        byte[] decrypted = memoryStream.ToArray();
                        return(Encoding.Unicode.GetString(decrypted));
                    }
                }
                catch { return(null); }
        }
        XmlElement VerifyInput2(MessageBuffer buf)
        {
            Message      msg2 = buf.CreateMessage();
            StringWriter sw   = new StringWriter();

            using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(sw))) {
                msg2.WriteMessage(w);
            }
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(sw.ToString());

            // decrypt the key with service certificate privkey
            PaddingMode  mode   = PaddingMode.PKCS7;          // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
            EncryptedXml encXml = new EncryptedXml(doc);

            encXml.Padding = mode;
            X509Certificate2    cert2 = new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
            nsmgr.AddNamespace("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
            nsmgr.AddNamespace("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            nsmgr.AddNamespace("e", "http://www.w3.org/2001/04/xmlenc#");
            nsmgr.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");
            XmlNode n = doc.SelectSingleNode("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);

            Assert.IsNotNull(n, "premise: enckey does not exist");
            string raw = n.InnerText;

            byte [] rawbytes             = Convert.FromBase64String(raw);
            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert2.PrivateKey;

            byte [] decryptedKey = EncryptedXml.DecryptKey(rawbytes, rsa, true);             //rsa.Decrypt (rawbytes, true);

#if false
            // create derived keys
            Dictionary <string, byte[]>  keys = new Dictionary <string, byte[]> ();
            InMemorySymmetricSecurityKey skey =
                new InMemorySymmetricSecurityKey(decryptedKey);
            foreach (XmlElement el in doc.SelectNodes("//o:Security/c:DerivedKeyToken", nsmgr))
            {
                n = el.SelectSingleNode("c:Offset", nsmgr);
                int offset = (n == null) ? 0 :
                             int.Parse(n.InnerText, CultureInfo.InvariantCulture);
                n = el.SelectSingleNode("c:Length", nsmgr);
                int length = (n == null) ? 32 :
                             int.Parse(n.InnerText, CultureInfo.InvariantCulture);
                n = el.SelectSingleNode("c:Label", nsmgr);
                byte [] label = (n == null) ? decryptedKey :
                                Convert.FromBase64String(n.InnerText);
                n = el.SelectSingleNode("c:Nonce", nsmgr);
                byte [] nonce = (n == null) ? new byte [0] :
                                Convert.FromBase64String(n.InnerText);
                byte [] derkey = skey.GenerateDerivedKey(
                    //SecurityAlgorithms.Psha1KeyDerivation,
                    "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
// FIXME: maybe due to the label, this key resolution somehow does not seem to work.
                    label,
                    nonce,
                    length * 8,
                    offset);

                keys [el.GetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
            }
#endif

            // decrypt the signature with the decrypted key
#if true
            n = doc.SelectSingleNode("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            raw      = n.InnerText;
            rawbytes = Convert.FromBase64String(raw);
            Rijndael aes = RijndaelManaged.Create();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key     = decryptedKey;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = mode;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(rawbytes, 0, rawbytes.Length);
            cs.Close();
            byte [] decryptedSignature = ms.ToArray();
#else
            Rijndael aes = RijndaelManaged.Create();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key     = decryptedKey;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = mode;

            EncryptedData ed = new EncryptedData();
            n = doc.SelectSingleNode("//o:Security/e:EncryptedData", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            ed.LoadXml(n as XmlElement);
            byte [] decryptedSignature = encXml.DecryptData(ed, aes);
#endif
//Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
//Console.Error.WriteLine ("============= Decrypted Signature End ===========");

            // decrypt the body with the decrypted key
#if true
            n = doc.SelectSingleNode("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            raw      = n.InnerText;
            rawbytes = Convert.FromBase64String(raw);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key = decryptedKey;
            ms      = new MemoryStream();
            cs      = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(rawbytes, 0, rawbytes.Length);
            cs.Close();
            byte [] decryptedBody = ms.ToArray();
#else
            // decrypt the body with the decrypted key
            EncryptedData ed2 = new EncryptedData();
            XmlElement    el  = doc.SelectSingleNode("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
            ed2.LoadXml(el);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key = decryptedKey;
            byte [] decryptedBody = encXml.DecryptData(ed2, aes);
#endif
//foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
            Console.Error.WriteLine(Encoding.UTF8.GetString(decryptedBody));
            Console.Error.WriteLine("============= Decrypted Body End ===========");

            // FIXME: find out what first 16 bytes mean.
            for (int mmm = 0; mmm < 16; mmm++)
            {
                decryptedBody [mmm] = 0x20;
            }
            doc.LoadXml(Encoding.UTF8.GetString(decryptedBody));
            Assert.AreEqual("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
            Assert.AreEqual("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");

            return(doc.DocumentElement);
        }
        /// <summary>
        /// AES 解密
        /// </summary>
        /// <param name="data">需要解密的数据</param>
        /// <param name="key">密钥</param>
        /// <param name="vector">向量</param>
        /// <returns></returns>
        public static string AESDecrypt(string data, string key, string vector)
        {
            MemoryStream memoryStream   = null;
            MemoryStream originalMemory = null;
            CryptoStream cryptoStream   = null;
            Rijndael     rijndael       = null;

            try
            {
                Byte[] encryptedBytes = Convert.FromBase64String(data);

                Byte[] byteKeys = new Byte[32];
                Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(byteKeys.Length)), byteKeys, byteKeys.Length);
                Byte[] byteVectors = new Byte[16];
                Array.Copy(Encoding.UTF8.GetBytes(vector.PadRight(byteVectors.Length)), byteVectors, byteVectors.Length);

                Byte[] original = null;

                rijndael = Rijndael.Create();
                using (memoryStream = new MemoryStream(encryptedBytes))
                {
                    using (cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(byteKeys, byteVectors), CryptoStreamMode.Read))
                    {
                        using (originalMemory = new MemoryStream())
                        {
                            Byte[] Buffer    = new Byte[1024];
                            Int32  readBytes = 0;
                            while ((readBytes = cryptoStream.Read(Buffer, 0, Buffer.Length)) > 0)
                            {
                                originalMemory.Write(Buffer, 0, readBytes);
                            }
                            original = originalMemory.ToArray();
                        }
                    }
                }
                return(Encoding.UTF8.GetString(original));
            }
            catch
            {
                throw;
            }
            finally
            {
                if (originalMemory != null)
                {
                    originalMemory.Close();
                }
                if (cryptoStream != null)
                {
                    cryptoStream.Close();
                }
                if (memoryStream != null)
                {
                    memoryStream.Close();
                }
                if (rijndael != null)
                {
                    rijndael.Clear();
                }
            }
        }
        public static string Decrypt(string encrypted, string password)
        {
            //Convert the string to bytes
            byte[] cypher = Convert.FromBase64String(encrypted);

            //convert password to key
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, SALT);
            string             decrypted;

            //Create instance of the rijndael encryption algorithm
            using (Rijndael rijndael = Rijndael.Create())
            {
                rijndael.Key = pdb.GetBytes(32);
                rijndael.IV  = cypher.Take(16).ToArray();

                using (MemoryStream memoryStream = new MemoryStream(cypher.Skip(16).ToArray()))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        using (StreamReader swDecrypt = new StreamReader(cryptoStream))
                        {
                            decrypted = swDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return(decrypted);
        }
Esempio n. 19
0
        // Decrypt a file into another file using a password
        public static bool Decrypt(string fileIn,
                                   string fileOut, string Password)
        {
            FileStream   fsIn  = null;
            FileStream   fsOut = null;
            CryptoStream cs    = null;

            try
            {
                // First we are going to open the file streams
                fsIn = new FileStream(fileIn,
                                      FileMode.Open, FileAccess.Read);
                fsOut = new FileStream(fileOut,
                                       FileMode.OpenOrCreate, FileAccess.Write);
                // Then we are going to derive a Key and an IV from
                // the Password and create an algorithm
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                                                                  new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                                                                               0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                Rijndael alg = Rijndael.Create();
                alg.Key = pdb.GetBytes(32);
                alg.IV  = pdb.GetBytes(16);
                // Now create a crypto stream through which we are going
                // to be pumping data.
                // Our fileOut is going to be receiving the Decrypted bytes.
                cs = new CryptoStream(fsOut,
                                      alg.CreateDecryptor(), CryptoStreamMode.Write);
                // Now will will initialize a buffer and will be
                // processing the input file in chunks.
                // This is done to avoid reading the whole file (which can be
                // huge) into memory.
                int    bufferLen = 4096;
                byte[] buffer    = new byte[bufferLen];
                int    bytesRead;
                do
                {
                    // read a chunk of data from the input file
                    bytesRead = fsIn.Read(buffer, 0, bufferLen);
                    // Decrypt it
                    cs.Write(buffer, 0, bytesRead);
                } while (bytesRead != 0);
                // close everything
            }
            catch (Exception e)
            {
                // Если что-то не так выбрасываем исключение
                Console.WriteLine("Error: {0}", e.Message);
                MessageBox.Show(
                    e.Message,
                    "Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information,
                    MessageBoxDefaultButton.Button1,
                    MessageBoxOptions.DefaultDesktopOnly);
                return(true);
            }
            try
            {
                if (cs != null)
                {
                    cs.Close();     // this will also close the unrelying fsOut stream
                }
                if (fsIn != null)
                {
                    fsIn.Close();
                }
            }
            catch (System.Security.Cryptography.CryptographicException eee)
            {
                //Console.WriteLine("Error: {0}", e.Message);
                MessageBox.Show(
                    "Password is'n correct",
                    "Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information,
                    MessageBoxDefaultButton.Button1,
                    MessageBoxOptions.DefaultDesktopOnly);
                cs.Clear();
                cs.Close();
                return(true);
            }

            return(false);
        }
Esempio n. 20
0
            // FIXME	[KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
            //			Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Decrypt)]
            public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
            {
                if (encryptedData == null)
                {
                    throw new ArgumentNullException("encryptedData");
                }

                byte[] decdata = null;

                Rijndael aes        = Rijndael.Create();
                RSA      rsa        = GetKey(scope);
                int      headerSize = (rsa.KeySize >> 3);
                bool     valid1     = (encryptedData.Length >= headerSize);

                if (!valid1)
                {
                    headerSize = encryptedData.Length;
                }

                byte[] header = new byte[headerSize];
                Buffer.BlockCopy(encryptedData, 0, header, 0, headerSize);

                byte[] secret = null;
                byte[] key    = null;
                byte[] iv     = null;
                bool   valid2 = false;
                bool   valid3 = false;
                bool   valid4 = false;
                SHA256 hash   = SHA256.Create();

                try
                {
                    try
                    {
                        RSAOAEPKeyExchangeDeformatter deformatter = new RSAOAEPKeyExchangeDeformatter(rsa);
                        secret = deformatter.DecryptKeyExchange(header);
                        valid2 = (secret.Length == 68);
                    }
                    catch
                    {
                        valid2 = false;
                    }

                    if (!valid2)
                    {
                        secret = new byte[68];
                    }

                    // known values for structure (version 1 or 2)
                    valid3 = ((secret[1] == 16) && (secret[18] == 16) && (secret[35] == 32));

                    key = new byte[16];
                    Buffer.BlockCopy(secret, 2, key, 0, 16);
                    iv = new byte[16];
                    Buffer.BlockCopy(secret, 19, iv, 0, 16);

                    if ((optionalEntropy != null) && (optionalEntropy.Length > 0))
                    {
                        // the decrypted data won't be valid if the entropy isn't
                        // the same as the one used to protect (encrypt) it
                        byte[] mask = hash.ComputeHash(optionalEntropy);
                        for (int i = 0; i < 16; i++)
                        {
                            key[i] ^= mask[i];
                            iv[i]  ^= mask[i + 16];
                        }
                        valid3 &= (secret[0] == 2); // with entropy
                    }
                    else
                    {
                        valid3 &= (secret[0] == 1); // without entropy
                    }

                    using (MemoryStream ms = new MemoryStream())
                    {
                        ICryptoTransform t = aes.CreateDecryptor(key, iv);
                        using (CryptoStream cs = new CryptoStream(ms, t, CryptoStreamMode.Write))
                        {
                            try
                            {
                                cs.Write(encryptedData, headerSize, encryptedData.Length - headerSize);
                                cs.Close();
                            }
                            catch
                            {
                                // whatever, we keep going
                            }
                        }
                        decdata = ms.ToArray();
                    }

                    byte[] digest = hash.ComputeHash(decdata);
                    valid4 = true;
                    for (int i = 0; i < 32; i++)
                    {
                        if (digest[i] != secret[36 + i])
                        {
                            valid4 = false;
                        }
                    }
                }
                finally
                {
                    if (key != null)
                    {
                        Array.Clear(key, 0, key.Length);
                        key = null;
                    }
                    if (secret != null)
                    {
                        Array.Clear(secret, 0, secret.Length);
                        secret = null;
                    }
                    if (iv != null)
                    {
                        Array.Clear(iv, 0, iv.Length);
                        iv = null;
                    }
                    aes.Clear();
                    hash.Clear();
                }

                // single point of error (also limits timing informations)
                if (!valid1 || !valid2 || !valid3 || !valid4)
                {
                    if (decdata != null)
                    {
                        Array.Clear(decdata, 0, decdata.Length);
                        decdata = null;
                    }
                    throw new CryptographicException("Invalid data.");
                }
                return(decdata);
            }
Esempio n. 21
0
        private int FinalizeInitialize(String filename, String passphrase)
        {
            try
            {
                core.InitializeKeys(passphrase);
            }
            catch
            {
                Console.Error.WriteLine("Invalid passphrase");
                return(1);
            }

            StreamReader sr       = new StreamReader(Path.Combine(core.ApplicationDataFolder, "identity"));
            String       username = sr.ReadLine();
            String       email    = sr.ReadLine();

            sr.Close();

            username.Trim();
            email.Trim();

            Connect();

            ArrayList key  = new ArrayList(File.ReadAllBytes(Path.Combine(core.ApplicationDataFolder, "answers.key")));
            AESInfo   info = new AESInfo();

            info.key = (byte[])key.GetRange(0, Crypto.AESKeySize / 8).ToArray(Type.GetType("System.Byte"));
            info.IV  =
                (byte[])key.GetRange(Crypto.AESKeySize / 8, Crypto.AESIVSize / 8).ToArray(Type.GetType("System.Byte"));

            Rijndael aes = Rijndael.Create();

            String e_macpass = File.ReadAllText(filename);

            e_macpass = Crypto.StripMessage(e_macpass);

            byte[] macpass =
                Crypto.AESDecrypt(Convert.FromBase64String(e_macpass), aes.CreateDecryptor(info.key, info.IV));

            HMAC hmac = HMACSHA1.Create();

            hmac.Key = macpass;
            byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(core.PublicKey));

            try
            {
                if (server.InitKeySet_SendPublicKey(username, email, core.PublicKey, Convert.ToBase64String(hash)))
                {
                    Console.WriteLine("Public key successfully sent.");
                    File.Delete(Path.Combine(core.ApplicationDataFolder, "answers"));
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }

            File.Delete(Path.Combine(core.ApplicationDataFolder, "answers.key"));

            return(0);
        }
Esempio n. 22
0
 public SyncIOEncryptionRijndael(Rijndael rijObject)
 {
     _rijObj    = rijObject;
     _encryptor = _rijObj.CreateEncryptor();
     _decryptor = _rijObj.CreateDecryptor();
 }
Esempio n. 23
0
        // Decrypt a byte array into a byte array using a key and an IV

        public static byte[] Decrypt(byte[] cipherData,
                                     byte[] Key, byte[] IV)
        {
            // Create a MemoryStream that is going to accept the

            // decrypted bytes

            MemoryStream ms = new MemoryStream();

            // Create a symmetric algorithm.

            // We are going to use Rijndael because it is strong and

            // available on all platforms.

            // You can use other algorithms, to do so substitute the next

            // line with something like

            //     TripleDES alg = TripleDES.Create();

            Rijndael alg = Rijndael.Create();

            // Now set the key and the IV.

            // We need the IV (Initialization Vector) because the algorithm

            // is operating in its default

            // mode called CBC (Cipher Block Chaining). The IV is XORed with

            // the first block (8 byte)

            // of the data after it is decrypted, and then each decrypted

            // block is XORed with the previous

            // cipher block. This is done to make encryption more secure.

            // There is also a mode called ECB which does not need an IV,

            // but it is much less secure.

            alg.Key = Key;
            alg.IV  = IV;

            // Create a CryptoStream through which we are going to be

            // pumping our data.

            // CryptoStreamMode.Write means that we are going to be

            // writing data to the stream

            // and the output will be written in the MemoryStream

            // we have provided.

            CryptoStream cs = new CryptoStream(ms,
                                               alg.CreateDecryptor(), CryptoStreamMode.Write);

            // Write the data and make it do the decryption

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

            // Close the crypto stream (or do FlushFinalBlock).

            // This will tell it that we have done our decryption

            // and there is no more data coming in,

            // and it is now a good time to remove the padding

            // and finalize the decryption process.

            cs.Close();

            // Now get the decrypted data from the MemoryStream.

            // Some people make a mistake of using GetBuffer() here,

            // which is not the right way.

            byte[] decryptedData = ms.ToArray();

            return(decryptedData);
        }
Esempio n. 24
0
        /// <summary>
        /// Decrypt DES encrypted ScopedPdu
        /// </summary>
        /// <param name="encryptedData">Source data buffer</param>
        /// <param name="engineBoots">Engine boots.</param>
        /// <param name="engineTime">Engine time.</param>
        /// <param name="key">Decryption key. Key length has to be 32 bytes in length or longer (bytes beyond 32 bytes are ignored).</param>
        /// <param name="privacyParameters">Privacy parameters extracted from USM header</param>
        /// <returns>Decrypted byte array</returns>
        /// <exception cref="ArgumentNullException">Thrown when encrypted data is null or length == 0</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key length is less then 32 byte or if privacy parameters
        /// argument is null or length other then 8 bytes</exception>
        private static byte[] Decrypt(byte[] encryptedData, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

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

            if (key.Length < KeyBytes)
            {
                throw new ArgumentOutOfRangeException("key", "Invalid key length");
            }

            byte[] iv         = new byte[16];
            byte[] bootsBytes = BitConverter.GetBytes(engineBoots);
            iv[0] = bootsBytes[3];
            iv[1] = bootsBytes[2];
            iv[2] = bootsBytes[1];
            iv[3] = bootsBytes[0];
            byte[] timeBytes = BitConverter.GetBytes(engineTime);
            iv[4] = timeBytes[3];
            iv[5] = timeBytes[2];
            iv[6] = timeBytes[1];
            iv[7] = timeBytes[0];

            // Copy salt value to the iv array
            Buffer.BlockCopy(privacyParameters, 0, iv, 8, PrivacyParametersLength);

            // now do CFB decryption of the encrypted data
            using (Rijndael rm = Rijndael.Create())
            {
                rm.KeySize      = KeyBytes * 8;
                rm.FeedbackSize = 128;
                rm.BlockSize    = 128;
                rm.Padding      = PaddingMode.Zeros;
                rm.Mode         = CipherMode.CFB;
                if (key.Length > KeyBytes)
                {
                    byte[] normKey = new byte[KeyBytes];
                    Buffer.BlockCopy(key, 0, normKey, 0, KeyBytes);
                    rm.Key = normKey;
                }
                else
                {
                    rm.Key = key;
                }

                rm.IV = iv;
                using (ICryptoTransform cryptor = rm.CreateDecryptor())
                {
                    // We need to make sure that cryptedData is a collection of 128 byte blocks
                    byte[] decryptedData;
                    if ((encryptedData.Length % KeyBytes) != 0)
                    {
                        byte[] buffer = new byte[encryptedData.Length];
                        Buffer.BlockCopy(encryptedData, 0, buffer, 0, encryptedData.Length);
                        int    div           = (int)Math.Floor(buffer.Length / (double)16);
                        int    newLength     = (div + 1) * 16;
                        byte[] decryptBuffer = new byte[newLength];
                        Buffer.BlockCopy(buffer, 0, decryptBuffer, 0, buffer.Length);
                        decryptedData = cryptor.TransformFinalBlock(decryptBuffer, 0, decryptBuffer.Length);

                        // now remove padding
                        Buffer.BlockCopy(decryptedData, 0, buffer, 0, encryptedData.Length);
                        return(buffer);
                    }

                    decryptedData = cryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
                    return(decryptedData);
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Decrypt <see cref="ScopedPdu"/> BER encoded byte array.
        /// </summary>
        /// <param name="cryptedData">Encrypted data byte array</param>
        /// <param name="offset">Offset within the buffer to start decryption process from</param>
        /// <param name="length">Length of data to decrypt</param>
        /// <param name="key">Decryption key</param>
        /// <param name="engineBoots">Authoritative engine boots value. Retrieved as part of SNMP v3 discovery procedure</param>
        /// <param name="engineTime">Authoritative engine time value. Retrieved as part of SNMP v3 discovery procedure</param>
        /// <param name="privacyParameters">Privacy parameters parsed from the incoming packet.</param>
        /// <returns>Byte array containing decrypted <see cref="ScopedPdu"/> in BER encoded format.</returns>
        public byte[] Decrypt(byte[] cryptedData, int offset, int length, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters)
        {
            if (key == null || key.Length < _keyBytes)
            {
                throw new ArgumentOutOfRangeException("decryptionKey", "Invalid key length");
            }

            byte[] iv = new byte[16];

            byte[] bootsBytes = BitConverter.GetBytes(engineBoots);
            iv[0] = bootsBytes[3];
            iv[1] = bootsBytes[2];
            iv[2] = bootsBytes[1];
            iv[3] = bootsBytes[0];
            byte[] timeBytes = BitConverter.GetBytes(engineTime);
            iv[4] = timeBytes[3];
            iv[5] = timeBytes[2];
            iv[6] = timeBytes[1];
            iv[7] = timeBytes[0];

            // Copy salt value to the iv array
            Buffer.BlockCopy(privacyParameters, 0, iv, 8, 8);

            byte[] decryptedData = null;

            // now do CFB decryption of the encrypted data
            Rijndael rm = Rijndael.Create();

            rm.KeySize      = _keyBytes * 8;
            rm.FeedbackSize = 128;
            rm.BlockSize    = 128;
            rm.Padding      = PaddingMode.Zeros;
            rm.Mode         = CipherMode.CFB;
            if (key.Length > MinimumKeyLength)
            {
                byte[] normKey = new byte[MinimumKeyLength];
                Buffer.BlockCopy(key, 0, normKey, 0, MinimumKeyLength);
                rm.Key = normKey;
            }
            else
            {
                rm.Key = key;
            }
            rm.IV = iv;
            System.Security.Cryptography.ICryptoTransform cryptor;
            cryptor = rm.CreateDecryptor();

            // We need to make sure that cryptedData is a collection of 128 byte blocks
            if ((cryptedData.Length % _keyBytes) != 0)
            {
                byte[] buffer = new byte[length];
                Buffer.BlockCopy(cryptedData, offset, buffer, 0, length);
                int    div           = (int)Math.Floor(buffer.Length / (double)16);
                int    newLength     = (div + 1) * 16;
                byte[] decryptBuffer = new byte[newLength];
                Buffer.BlockCopy(buffer, 0, decryptBuffer, 0, buffer.Length);
                decryptedData = cryptor.TransformFinalBlock(decryptBuffer, 0, decryptBuffer.Length);
                // now remove padding
                Buffer.BlockCopy(decryptedData, 0, buffer, 0, length);
                return(buffer);
            }

            decryptedData = cryptor.TransformFinalBlock(cryptedData, offset, length);

            return(decryptedData);
        }
Esempio n. 26
0
        private void btnSaveImportedData_Click(object sender, EventArgs e)
        {
            List <CSOMaster> oListSOMaster = new List <CSOMaster>();

            openFileDialog1.InitialDirectory = @"H:\";
            openFileDialog1.Filter           = "Sales File (*.Salexp)|*.Salexp";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                IFormatter formatter = new BinaryFormatter();
                if (File.Exists(openFileDialog1.FileName))
                {
                    using (Stream stream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        byte[]       baKey        = { 51, 208, 75, 59, 223, 134, 241, 155, 170, 229, 177, 160, 246, 71, 77, 141, 66, 7, 223, 103, 97, 80, 235, 82, 94, 107, 226, 190, 76, 94, 31, 43 };
                        byte[]       baIV         = { 142, 96, 41, 14, 206, 132, 173, 19, 12, 50, 124, 121, 42, 27, 35, 9 };
                        Rijndael     rijndael     = Rijndael.Create();
                        CryptoStream cryptoStream = new CryptoStream(stream, rijndael.CreateDecryptor(baKey, baIV), CryptoStreamMode.Read);

                        //
                        oListSOMaster = (List <CSOMaster>)formatter.Deserialize(cryptoStream);
                        //
                        cryptoStream.Close();
                    }
                }
            }

            if (oListSOMaster.Count > 0)
            {
                if (currentBranch.CompBrn_OId.Trim() == ((CSOMaster)oListSOMaster[0]).ExportedToBrnOID.Trim())
                {
                    //Save data to t_somstr and t_sodet
                    if (oListSOMaster.Count > 0)
                    {
                        CResult oResult = new CResult();
                        CSOBO   oSOBO   = new CSOBO();
                        if (oListSOMaster.Count > 0)
                        {
                            foreach (CSOMaster oSOMaster in oListSOMaster)
                            {
                                oResult = oSOBO.Import(oSOMaster, currentBranch.CompBrn_Branch, currentBranch.CompBrn_OId);

                                if (!oResult.IsSuccess)
                                {
                                    MessageBox.Show(oResult.ErrMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    break;
                                }
                            }

                            if (oResult.IsSuccess)
                            {
                                MessageBox.Show("Successfully Done ", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }

                            // UPdate inventory
                        }
                    }
                }
                else
                {
                    MessageBox.Show("You can not access the selected file.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    oListSOMaster = null;
                }
            }
        }
Esempio n. 27
0
        public static void Decrypt(string FileName, string outFileName, string secret)
        {
            FileStream fileOutStream = File.Create(outFileName);

            using (Rijndael rijndael = GetRijndael(secret))
                using (FileStream fileStream = File.OpenRead(FileName))
                    using (CryptoStream cryptoStream = new CryptoStream(fileOutStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        fileStream.CopyTo(cryptoStream);
                    }
        }
Esempio n. 28
0
            /// <summary>
            ///AES 解密
            /// </summary>
            /// <param name="decryptString">待解密密文</param>
            /// <param name="decryptKey">解密密钥</param>
            /// <returns></returns>
            public static string Decrypt(string decryptString, string decryptKey)
            {
                string returnValue = "";

                byte[]   temp        = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
                Rijndael AESProvider = Rijndael.Create();

                try
                {
                    string defaultKey = "3B2hb2oYHpmZrFflfdmSon1x";
                    if (string.IsNullOrEmpty(decryptKey))
                    {
                        decryptKey = defaultKey;
                    }
                    if (decryptKey.Length < 24)
                    {
                        decryptKey = decryptKey + defaultKey.Substring(0, 24 - decryptKey.Length);
                    }
                    if (decryptKey.Length > 24)
                    {
                        decryptKey = decryptKey.Substring(0, 24);
                    }
                    byte[] byteDecryptString = Convert.FromBase64String(decryptString);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, AESProvider.CreateDecryptor(Encoding.UTF8.GetBytes(decryptKey), temp), CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(byteDecryptString, 0, byteDecryptString.Length);
                            cryptoStream.FlushFinalBlock();
                            returnValue = Encoding.UTF8.GetString(memoryStream.ToArray());
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return(returnValue);
            }
Esempio n. 29
0
        private void btnSaveAndPrint_Click(object sender, EventArgs e)
        {
            if (defaultUserMode)
            {
                if (ValidateToBSaveData())
                {
                    CResult   oResult   = new CResult();
                    CSOBO     oSOBO     = new CSOBO();
                    CSOMaster oSOMaster = GetToSOFormData();

                    if (oSOMaster.SOMstr_DetailsList.Count > 0)
                    {
                        oResult = oSOBO.Create(oSOMaster);

                        if (oResult.IsSuccess)
                        {
                            //MessageBox.Show("Successfully Done. ", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            string SOMstID = (string)oResult.Data;
                            this.GenerateInvoiceReport(SOMstID);
                            this.ClearAll();
                            txtbarcode.Select();
                            this.LoadItemList();
                        }
                        else
                        {
                            MessageBox.Show(oResult.ErrMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                // Advance Start

                string m_sAdvanceConfigFileName = "AdvanceConfigAndLogFile.config";

                if (ValidateToBSaveData())
                {
                    CResult   oResult   = new CResult();
                    CSOBO     oSOBO     = new CSOBO();
                    CSOMaster oSOMaster = GetToSOFormData();

                    if (oSOMaster.SOMstr_DetailsList.Count > 0)
                    {
                        List <CSOMaster> oListSOMaster = new List <CSOMaster>();

                        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        if (File.Exists(m_sAdvanceConfigFileName))
                        {
                            using (Stream stream = new FileStream(m_sAdvanceConfigFileName, FileMode.Open, FileAccess.Read, FileShare.None))
                            {
                                byte[]       baKey        = { 51, 208, 75, 59, 223, 134, 241, 155, 170, 229, 177, 160, 246, 71, 77, 141, 66, 7, 223, 103, 97, 80, 235, 82, 94, 107, 226, 190, 76, 94, 31, 43 };
                                byte[]       baIV         = { 142, 96, 41, 14, 206, 132, 173, 19, 12, 50, 124, 121, 42, 27, 35, 9 };
                                Rijndael     rijndael     = Rijndael.Create();
                                CryptoStream cryptoStream = new CryptoStream(stream, rijndael.CreateDecryptor(baKey, baIV), CryptoStreamMode.Read);
                                //
                                oListSOMaster = (List <CSOMaster>)formatter.Deserialize(cryptoStream);

                                //
                                cryptoStream.Close();
                            }
                        }
                        oListSOMaster.Add(oSOMaster);
                        formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        using (Stream stream = new FileStream(m_sAdvanceConfigFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                        {
                            byte[]       baKey        = { 51, 208, 75, 59, 223, 134, 241, 155, 170, 229, 177, 160, 246, 71, 77, 141, 66, 7, 223, 103, 97, 80, 235, 82, 94, 107, 226, 190, 76, 94, 31, 43 };
                            byte[]       baIV         = { 142, 96, 41, 14, 206, 132, 173, 19, 12, 50, 124, 121, 42, 27, 35, 9 };
                            Rijndael     rijndael     = Rijndael.Create();
                            CryptoStream cryptoStream = new CryptoStream(stream, rijndael.CreateEncryptor(baKey, baIV), CryptoStreamMode.Write);
                            //
                            formatter.Serialize(cryptoStream, oListSOMaster);

                            //
                            cryptoStream.Close();
                        }
                        {
                            CResult oResult2 = new CResult();
                            CGRBO   oGRBO    = new CGRBO();
                            oResult2 = oGRBO.ReduceByItemOID(oSOMaster.SOMstr_DetailsList);
                        }

                        //this.LoadItemList();
                        this.GenerateInvoiceReport(oSOMaster);
                        this.ClearAll();
                        txtbarcode.Select();
                    }
                    //
                }
                // Advance End
            }
        }
Esempio n. 30
0
        public static string Decrypt(
            string value,
            string vector,
            string key)
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                /*throw new Exception(
                 *  "O conteúdo a ser decriptado não pode " +
                 *  "ser uma string vazia.");*/
                return(string.Empty);
            }

            if (value.Length % 2 != 0)
            {
                /*throw new Exception(
                 *  "O conteúdo a ser decriptado é inválido.");*/
                return(string.Empty);
            }

            string   textoDecriptografado = string.Empty;
            Rijndael algoritmo            = null;

            try
            {
                using (algoritmo = InitRijndael(
                           key, vector))
                {
                    ICryptoTransform decryptor =
                        algoritmo.CreateDecryptor(
                            algoritmo.Key, algoritmo.IV);

                    using (MemoryStream streamTextoEncriptado =
                               new MemoryStream(
                                   HexStringToArrayBytes(value)))
                    {
                        using (CryptoStream csStream = new CryptoStream(
                                   streamTextoEncriptado, decryptor,
                                   CryptoStreamMode.Read))
                        {
                            using (StreamReader reader =
                                       new StreamReader(csStream))
                            {
                                textoDecriptografado =
                                    reader.ReadToEnd();
                            }
                        }
                    }
                }
            }
            catch
            {
                textoDecriptografado = string.Empty;
            }
            finally
            {
                if (algoritmo != null)
                {
                    algoritmo.Clear();
                }
            }
            return(textoDecriptografado);
        }