public static string Encrypt(string data, string password) { if (String.IsNullOrEmpty(data)) { return(null); } if (String.IsNullOrEmpty(password)) { return(null); } // setup the encryption algorithm Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, 8); Rijndael aes = Rijndael.Create(); aes.IV = keyGenerator.GetBytes(aes.BlockSize / 8); aes.Key = keyGenerator.GetBytes(aes.KeySize / 8); // encrypt the data byte[] rawData = Encoding.Unicode.GetBytes(data); using (MemoryStream memoryStream = new MemoryStream()) try { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length); cryptoStream.Write(rawData, 0, rawData.Length); cryptoStream.Close(); byte[] encrypted = memoryStream.ToArray(); return(Encoding.Unicode.GetString(encrypted)); } } catch { return(null); } }
public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) { if (userData == null) { throw new ArgumentNullException("userData"); } Rijndael aes = Rijndael.Create(); aes.KeySize = 128; byte[]? encdata = null; using (MemoryStream ms = new MemoryStream()) { ICryptoTransform t = aes.CreateEncryptor(); using CryptoStream cs = new CryptoStream(ms, t, CryptoStreamMode.Write); cs.Write(userData, 0, userData.Length); cs.Close(); encdata = ms.ToArray(); } byte[]? key = null; byte[]? iv = null; byte[]? secret = null; byte[]? header = null; SHA256 hash = SHA256.Create(); try { key = aes.Key; iv = aes.IV; secret = new byte[1 + 1 + 16 + 1 + 16 + 1 + 32]; byte[] digest = hash.ComputeHash(userData); if ((optionalEntropy != null) && (optionalEntropy.Length > 0)) { // the same optionalEntropy will be required to get the data back byte[] mask = hash.ComputeHash(optionalEntropy); for (int i = 0; i < 16; i++) { key[i] ^= mask[i]; iv[i] ^= mask[i + 16]; } secret[0] = 2; // entropy } else { secret[0] = 1; // without entropy } secret[1] = 16; // key size Buffer.BlockCopy(key, 0, secret, 2, 16); secret[18] = 16; // iv size Buffer.BlockCopy(iv, 0, secret, 19, 16); secret[35] = 32; // digest size Buffer.BlockCopy(digest, 0, secret, 36, 32); RSAOAEPKeyExchangeFormatter formatter = new RSAOAEPKeyExchangeFormatter(GetKey(scope)); header = formatter.CreateKeyExchange(secret); } 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(); } byte[] result = new byte[header.Length + encdata.Length]; Buffer.BlockCopy(header, 0, result, 0, header.Length); Buffer.BlockCopy(encdata, 0, result, header.Length, encdata.Length); return(result); }
public void EncryptDecryptFile(Stream srcStream, Stream destStream, string password, bool decrypt) { CryptoStream cs = null; try { Rijndael cryptic = Rijndael.Create(); PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); cryptic.Key = pdb.GetBytes(32); cryptic.IV = pdb.GetBytes(16); cs = new CryptoStream(destStream, (decrypt ? cryptic.CreateDecryptor() : cryptic.CreateEncryptor()), CryptoStreamMode.Write); int data; double prog = 0; int progTot = 0; while ((data = srcStream.ReadByte()) != -1) { if (_cancel) { cs.Close(); cs.Dispose(); if (Cancelled != null) { Cancelled(this, new EventArgs()); } return; } cs.WriteByte((byte)data); if (ProgressChanged != null) { prog++; if (Math.Floor((100 * prog) / srcStream.Length) > progTot) { progTot = Convert.ToInt16((100 * prog) / srcStream.Length); ProgressChanged(this, new ProgressChangedEventArgs(progTot, null)); } } } } finally { cs.Close(); cs.Dispose(); } }
/// <summary> /// AES加密 /// </summary> /// <param name="encryptString">待加密的密文</param> /// <param name="encryptKey">加密密匙</param> /// <returns></returns> public static string Encrypt(string encryptString, string encryptKey) { string returnValue; byte[] temp = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ=="); Rijndael AESProvider = Rijndael.Create(); try { string defaultKey = "3B2hb2oYHpmZrFflfdmSon1x"; if (string.IsNullOrEmpty(encryptKey)) { encryptKey = defaultKey; } if (encryptKey.Length < 24) { encryptKey = encryptKey + defaultKey.Substring(0, 24 - encryptKey.Length); } if (encryptKey.Length > 24) { encryptKey = encryptKey.Substring(0, 24); } byte[] byteEncryptString = Encoding.UTF8.GetBytes(encryptString); using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, AESProvider.CreateEncryptor(Encoding.UTF8.GetBytes(encryptKey), temp), CryptoStreamMode.Write)) { cryptoStream.Write(byteEncryptString, 0, byteEncryptString.Length); cryptoStream.FlushFinalBlock(); returnValue = Convert.ToBase64String(memoryStream.ToArray()); } } } catch (Exception ex) { throw ex; } return(returnValue); }
//// Key for TripleDES encryption //public static byte[] _key = { 21, 10, 64, 10, 100, 40, 200, 4, // 21, 54, 65, 246, 5, 62, 1, 54, // 54, 6, 8, 9, 65, 4, 65, 9}; //private static byte[] _iv = { 0, 0, 0, 0, 0, 0, 0, 0 }; //static public string Write(string original) //{ // return Write(original, _key, _iv); //} //static public string Write(string str, byte []rgbKey,byte [] rgbIV) //{ // //TripleDES tdes = new TripleDESCryptoServiceProvider(); // //Rijndael RijndaelAlg = Rijndael.Create(); // //MemoryStream ms = new MemoryStream(); // //CryptoStream cs = new CryptoStream(ms, RijndaelAlg.CreateEncryptor(RijndaelAlg.Key, RijndaelAlg.IV), CryptoStreamMode.Write); // //byte[] d = Encoding.ASCII.GetBytes(str); // //cs.Write(d, 0, d.Length); // //cs.WriteByte(0); // //cs.Flush(); // //byte[] buffer = new byte[ms.Length]; // //ms.Position = 0; // //ms.Read(buffer, 0, buffer.Length); // ////cs.Close(); // ////ms.Close(); // //ms.Position = 0; // //cs = new CryptoStream(ms, RijndaelAlg.CreateDecryptor(RijndaelAlg.Key, RijndaelAlg.IV), CryptoStreamMode.Read); // //cs.ReadByte(); // //return Convert.ToBase64String(buffer); // return Convert.ToBase64String(Encoding.ASCII.GetBytes(str)); //} //static public string Read(string str) //{ // return Read(str, _key, _iv); //} //static public string Read(string str, byte[] rgbKey, byte[] rgbIV) //{ //MemoryStream ms = new MemoryStream(); //byte[] data = Convert.FromBase64String(str); //ms.Write(data, 0, data.Length); //ms.Position = 0; //TripleDES tdes = new TripleDESCryptoServiceProvider(); //CryptoStream cs = new CryptoStream(ms, tdes.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Read); //StringBuilder SB = new StringBuilder(); //int ch; //for (int i = 0; i < ms.Length; i++) //{ // ch = cs.ReadByte(); // if (ch == 0) // break; // SB.Append(Convert.ToChar(ch)); //} //cs.Close(); //ms.Close(); //return ms.ToString(); //return Encoding.ASCII.GetString(Convert.FromBase64String(str)); //} // Encrypt a byte array into a byte array using a key and an IV public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) { // Create a MemoryStream that is going to accept the encrypted 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 before it is encrypted, and then each encrypted block is XORed with the // following block of plaintext. 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.CreateEncryptor(), CryptoStreamMode.Write); // Write the data and make it do the encryption cs.Write(clearData, 0, clearData.Length); // Close the crypto stream (or do FlushFinalBlock). // This will tell it that we have done our encryption and there is no more data coming in, // and it is now a good time to apply the padding and finalize the encryption process. cs.Close(); // Now get the encrypted data from the MemoryStream. // Some people make a mistake of using GetBuffer() here, which is not the right way. byte[] encryptedData = ms.ToArray(); return(encryptedData); }
private void btn_EncryptFile_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Title = "Select file"; dialog.InitialDirectory = ".\\"; dialog.Filter = "exe files (*.exe)|*.exe"; if (dialog.ShowDialog() != DialogResult.OK) { return; } // First we are going to open the file streams string fileOut; if (dialog.FileName.EndsWith(".exe")) { fileOut = dialog.FileName.Substring(0, dialog.FileName.Length - 4) + ".db"; } else { fileOut = dialog.FileName + ".db"; } FileStream fsIn = new FileStream(dialog.FileName, FileMode.Open, FileAccess.Read); FileStream fsOut = new FileStream(fileOut, FileMode.Create, FileAccess.Write); // Then we are going to derive a Key and an IV from the // Password and create an algorithm PasswordDeriveBytes pdb = new PasswordDeriveBytes(FConstants.StringCipherKey, 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 encrypted bytes. CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), 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; long bytes = 0; do { // read a chunk of data from the input file bytesRead = fsIn.Read(buffer, 0, bufferLen); // encrypt it cs.Write(buffer, 0, bytesRead); richTextBox_EncryptionEncrypted.Text = $"Encrypting {bytes+=bytesRead} bytes"; } while (bytesRead != 0); // close everything // this will also close the unrelying fsOut stream cs.Close(); fsIn.Close(); richTextBox_EncryptionEncrypted.Text += "...Done."; }
public Task <bool> UploadFile(string destination, string file) { return(Task.Run(() => { try { var remoteExplorer = new RemoteExplorer(); if (destination.Count(e => e == '/') > 1) { int index = destination.IndexOf('/', destination.IndexOf('/') + 1); var rootFolder = destination.Substring(0, index); var folder = GetFolder(rootFolder).Result; if (folder.HasCryptoKeys) { Rijndael rijndael = Rijndael.Create(); rijndael.Key = folder.Key; rijndael.IV = folder.IV; using (var stream = new CryptoStream(File.OpenRead(file), rijndael.CreateEncryptor(), CryptoStreamMode.Read)) { return remoteExplorer.UploadFile(destination, stream); } } } using (var stream = File.OpenRead(file)) { return remoteExplorer.UploadFile(destination, stream); } } catch (Exception ex) { Insights.Report(ex); return false; } })); }
public static void Encrypt(string fileName, string outFileName, string secret) { using (FileStream fileOutStream = File.Create(outFileName)) using (Rijndael rijndael = GetRijndael(secret)) using (FileStream fileStream = File.OpenRead(fileName)) using (CryptoStream cryptoStream = new CryptoStream(fileOutStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write, true)) { fileStream.CopyTo(cryptoStream); } }
private static byte[] AESEncryptorMain(byte[] value) { try { // Setup encryption algorithm Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(secretKey, 8); Rijndael aes = Rijndael.Create(); aes.IV = keyGenerator.GetBytes(aes.BlockSize / 8); aes.Key = keyGenerator.GetBytes(aes.KeySize / 8); // Encrypt data using (MemoryStream memoryStream = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length); cryptoStream.Write(value, 0, value.Length); cryptoStream.Close(); byte[] encrypted = memoryStream.ToArray(); return(encrypted); } } catch (CryptographicException ex) { log.Write("AESEncryptorMain", ex.ToString(), System.Diagnostics.TraceEventType.Error); byte[] salt = new byte[1]; for (int i = 0; i < salt.Length; i++) { salt[i] = 0; } return(salt); } }
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); } } } }
public override void Encrypt(byte[] src, int offset, int len) { enc = aes.CreateEncryptor(Key, new byte[16]); enc.TransformBlock(src, offset, len, src, offset); }
public static byte[] Encrypt(byte[] data, byte[] key, byte[] iv) { using (Rijndael algorithm = Rijndael.Create()) using (ICryptoTransform encryptor = algorithm.CreateEncryptor(key, iv)) return(Crypta(data, key, iv, encryptor)); }
public String encryption(string plainText) { //Initial Setup: //------------------------------------------------------------------------------------------------------------------ String ciphertext = ""; //------------------------------------------------------------------------------------------------------------------ //Do Initial Error Checking before encryption: //------------------------------------------------------------------------------------------------------------------ if (plainText == null || plainText.Length <= 0) { throw new ArgumentException("plaintext"); } if (this.key == null || this.key.Length <= 0) { throw new ArgumentException("key"); } if (this.iv == null || this.iv.Length <= 0) { throw new ArgumentException("iv"); } //------------------------------------------------------------------------------------------------------------------ //Declare encrypted Byte Array: //------------------------------------------------------------------------------------------------------------------ byte[] encrypted; //------------------------------------------------------------------------------------------------------------------ //Encrypt plaintext: //------------------------------------------------------------------------------------------------------------------ using (Rijndael rij = Rijndael.Create()) { rij.Key = this.key; rij.IV = this.iv; ICryptoTransform encryptor = rij.CreateEncryptor(rij.Key, rij.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter westream = new StreamWriter(csEncrypt)) { westream.Write(plainText); } //END OF STREAM-WRITER. encrypted = msEncrypt.ToArray(); } //END OF CRYPTO_STREAM. } //END OF MEMORY-STREAM. } //END OF RIJNDAEL. //------------------------------------------------------------------------------------------------------------------ //Convert Byte array to string: //------------------------------------------------------------------------------------------------------------------ ciphertext = System.Text.Encoding.Default.GetString(encrypted); //------------------------------------------------------------------------------------------------------------------ //Return Encrypted String: //------------------------------------------------------------------------------------------------------------------ return(ciphertext); //------------------------------------------------------------------------------------------------------------------ }//END OF ENCRYPTION FUNCTION.
internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { switch (this.algorithmID) { case EncryptionAlgorithm.Des: DES des = (DES) new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = des.Key; } else { des.Key = bytesKey; this.encKey = des.Key; } if (this.initVec == null) { this.initVec = des.IV; } else { des.IV = this.initVec; } return(des.CreateEncryptor()); case EncryptionAlgorithm.Rc2: RC2 rc2 = (RC2) new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = rc2.Key; } else { rc2.Key = bytesKey; this.encKey = rc2.Key; } if (this.initVec == null) { this.initVec = rc2.IV; } else { rc2.IV = this.initVec; } return(rc2.CreateEncryptor()); case EncryptionAlgorithm.Rijndael: Rijndael rijndael = (Rijndael) new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = rijndael.Key; } else { rijndael.Key = bytesKey; this.encKey = rijndael.Key; } if (this.initVec == null) { this.initVec = rijndael.IV; } else { rijndael.IV = this.initVec; } return(rijndael.CreateEncryptor()); case EncryptionAlgorithm.TripleDes: TripleDES tripleDes = (TripleDES) new TripleDESCryptoServiceProvider(); tripleDes.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = tripleDes.Key; } else { tripleDes.Key = bytesKey; this.encKey = tripleDes.Key; } if (this.initVec == null) { this.initVec = tripleDes.IV; } else { tripleDes.IV = this.initVec; } return(tripleDes.CreateEncryptor()); default: throw new CryptographicException("Algorithm ID '" + (object)this.algorithmID + "' not supported."); } }
private void ExportData() { string m_sMasterExportFileName = DateTime.Now.ToString("dd-MMM-yyyy") + "_" + currentBranch.CompBrn_Name; saveFileDialog1.FileName = m_sMasterExportFileName; saveFileDialog1.InitialDirectory = @"H:\"; saveFileDialog1.Filter = "Master File (*.mstrexp)|*.mstrexp"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { m_sMasterExportFileName = saveFileDialog1.FileName; IFormatter formatter = new BinaryFormatter(); using (Stream stream = new FileStream(m_sMasterExportFileName, FileMode.Create, 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); // { CResult oResult; // UOM oResult = new CResult(); CUOMBO oUOMBO = new CUOMBO(); oResult = oUOMBO.ReadAll(); if (oResult.IsSuccess) { ArrayList oListUOM = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListUOM); } // Item Type oResult = new CResult(); CItemBO oItemBO = new CItemBO(); oResult = oItemBO.ReadAll(new CItemType()); if (oResult.IsSuccess) { ArrayList oListItemType = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListItemType); } // Item Group oResult = new CResult(); oItemBO = new CItemBO(); oResult = oItemBO.ReadAll(new CItemGroup()); if (oResult.IsSuccess) { ArrayList oListItemGroup = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListItemGroup); } // Item oResult = new CResult(); oItemBO = new CItemBO(); oResult = oItemBO.ReadAll(); if (oResult.IsSuccess) { ArrayList oListItem = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListItem); } // Reorder Level oResult = new CResult(); CReorderLevelBO oReorderLevelBO = new CReorderLevelBO(); oResult = oReorderLevelBO.ReadAllReorderLevelData(new CReorderLevel()); if (oResult.IsSuccess) { ArrayList oListReorderLevel = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListReorderLevel); } // Currency oResult = new CResult(); CCurrencyBO oCurrencyBO = new CCurrencyBO(); oResult = oCurrencyBO.ReadAll(); if (oResult.IsSuccess) { List <CCurrency> oListCurrency = (List <CCurrency>)oResult.Data; formatter.Serialize(cryptoStream, oListCurrency); } // Price Master oResult = new CResult(); CPriceMasterBO oPriceMasterBO = new CPriceMasterBO(); oResult = oPriceMasterBO.ReadAll(); if (oResult.IsSuccess) { ArrayList oListPriceMaster = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListPriceMaster); } // Customer oResult = new CResult(); CCustomerBO oCustomerBO = new CCustomerBO(); oResult = oCustomerBO.ReadAll(new CCustomer()); if (oResult.IsSuccess) { ArrayList oListCustomer = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListCustomer); } // Supplier oResult = new CResult(); CSupplierBO oSupplierBO = new CSupplierBO(); oResult = oSupplierBO.ReadAll(new CSupplier()); if (oResult.IsSuccess) { ArrayList oListSupplier = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListSupplier); } // Company oResult = new CResult(); CCompanyBO oCompanyBO = new CCompanyBO(); oResult = oCompanyBO.ReadAll(); if (oResult.IsSuccess) { List <CCompany> oListCompany = (List <CCompany>)oResult.Data; formatter.Serialize(cryptoStream, oListCompany); } // Company Branch oResult = new CResult(); CCompanyBranchBO oCompanyBranchBO = new CCompanyBranchBO(); oResult = oCompanyBranchBO.ReadAll(); if (oResult.IsSuccess) { List <CCompanyBranch> oListCompanyBranch = (List <CCompanyBranch>)oResult.Data; formatter.Serialize(cryptoStream, oListCompanyBranch); } // Company Vs CompanyBranch oResult = new CResult(); CCVBBO oCVBBO = new CCVBBO(); oResult = oCVBBO.ReadAllCVB(new CCVB()); if (oResult.IsSuccess) { ArrayList oListCVB = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListCVB); } // Inventory Location oResult = new CResult(); CLocBO oLocBO = new CLocBO(); oResult = oLocBO.ReadAll(); if (oResult.IsSuccess) { ArrayList oListLocation = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListLocation); } // CompanyBranch Vs Location oResult = new CResult(); oCVBBO = new CCVBBO(); oResult = oCVBBO.ReadAllBVL(new CCVB()); if (oResult.IsSuccess) { ArrayList oListCVB = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListCVB); } // Employee oResult = new CResult(); CEmployeeBO oEmployeeBO = new CEmployeeBO(); oResult = oEmployeeBO.ReadAllEmployee(new CEmployee()); if (oResult.IsSuccess) { ArrayList oListEmployee = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListEmployee); } // User oResult = new CResult(); CUserBO oUserBO = new CUserBO(); oResult = oUserBO.ReadAllUserData(new CUser()); if (oResult.IsSuccess) { ArrayList oListUser = (ArrayList)oResult.Data; formatter.Serialize(cryptoStream, oListUser); } } // cryptoStream.Close(); } } this.Close(); }
private static SecureString GenerateToken() { byte[] hash; Assembly asm = Assembly.GetEntryAssembly(); using (SHA256Managed sha = new SHA256Managed()) using (FileStream fs = File.OpenRead(asm.Location)) hash = sha.ComputeHash(fs); StringBuilder sb = new StringBuilder(); Random rand = new Random(_seed); /***Random Portion********/ //Algorithm 1 //int len = rand.Next(189, 350); //for (int i = rand.Next(15, 35); i < len; i += 2) // sb.Append((char)rand.Next(48, 122)); //Algorithm 2 //int len = rand.Next(53, 281); //int i = 0; //do { sb.Append((char)rand.Next(26, 114)); } //while (++i < len); //Algorithm 3 //int len = rand.Next(66, 252); //for (int i = 0; i < len; i += 3) // sb.Append(Convert.ToChar(Math.Floor(128 * rand.NextDouble()))); //Algorithm 4 //int len = rand.Next(21, 125); //for (int i = 0; i < len; i++) //{ // sb.Append((char)rand.Next(21, 125)) // .Replace((char)rand.Next(31, 120), // (char)rand.Next(24, 108)); //} //Algorithm 5 int len = rand.Next(54, 255); for (int i = 0; i < len; i += 2) { int jlen = rand.Next(12, 63); for (int j = 0; j < jlen; i += 3) { sb.Append((char)rand.Next(15, 82)); } } /*************************/ string value = sb.ToString(); byte[] data = Encoding.UTF8.GetBytes(value); string iv = GeneratePassword(0xa19c62); PasswordDeriveBytes pdb = new PasswordDeriveBytes(Encoding.UTF8.GetBytes(value), Encoding.UTF8.GetBytes(value)); using (Rijndael alg = Rijndael.Create()) { alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) using (CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(hash, 0, hash.Length); cs.Close(); data = ms.ToArray(); } } using (SHA256Managed sha = new SHA256Managed()) { SecureString result = new SecureString(); foreach (char s in BitConverter.ToString(sha.ComputeHash(data))) { result.AppendChar(s); } result.MakeReadOnly(); return(result); } }
public static string Encrypt(string plain, string password) { if (password == null) { return(plain); } //convert password to key Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, SALT); byte[] encrypted; byte[] iv; //Create instance of the rijndael encryption algorithm using (Rijndael rijndael = Rijndael.Create()) { rijndael.Key = pdb.GetBytes(32); rijndael.GenerateIV(); iv = rijndael.IV; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(cryptoStream)) { swEncrypt.Write(plain); } encrypted = memoryStream.ToArray(); } } } return(Convert.ToBase64String(iv.Concat(encrypted).ToArray())); }
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); }
public SyncIOEncryptionRijndael(Rijndael rijObject) { _rijObj = rijObject; _encryptor = _rijObj.CreateEncryptor(); _decryptor = _rijObj.CreateDecryptor(); }
// Encrypt a file into another file using a password public static void Encrypt(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, 0x4e, 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 encrypted bytes. CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), 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); // encrypt it cs.Write(buffer, 0, bytesRead); } while (bytesRead != 0); // close everything cs.Close(); // this will also close the unrelying fsOut stream fsIn.Close(); }
private byte[] Encrypt(byte[] clearData, string saltPhrase, string passPhrase) { Rijndael algorithm = NewSymmetricKeyAlgorithumFrom(saltPhrase, passPhrase); return(CryptoTransform(clearData, algorithm.CreateEncryptor())); }