static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher) { Byte[] CipherCalculated; Console.WriteLine("Encrypting the following bytes:"); PrintByteArray(Plain); Console.WriteLine("With the following Key:"); PrintByteArray(Key); Console.WriteLine("and IV:"); PrintByteArray(IV); Console.WriteLine("Expecting this ciphertext:"); PrintByteArray(Cipher); ICryptoTransform sse = aes.CreateEncryptor(Key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs.Write(Plain,0,Plain.Length); cs.FlushFinalBlock(); CipherCalculated = ms.ToArray(); cs.Close(); Console.WriteLine("Computed this cyphertext:"); PrintByteArray(CipherCalculated); if (!Compare(Cipher, CipherCalculated)) { Console.WriteLine("ERROR: result is different from the expected"); return false; } Console.WriteLine("OK"); return true; }
public static bool ForCodeCoverage() { AesManaged aes = new AesManaged(); using (ICryptoTransform cte = aes.CreateEncryptor(), ctd = aes.CreateDecryptor()) { byte[] plain1 = new byte[64]; for (int i = 0; i < plain1.Length; i++) plain1[i] = (byte)i; byte[] encr1 = cte.TransformFinalBlock(plain1, 0, plain1.Length); using(MemoryStream ms = new MemoryStream()) using(CryptoStream cs = new CryptoStream(ms, ctd, CryptoStreamMode.Write)) { cs.Write(encr1, 0, 16); cs.Write(encr1, 16, 16); cs.Write(encr1, 32, 16); cs.Write(encr1, 48, encr1.Length-48); cs.FlushFinalBlock(); byte[] plain2 = ms.ToArray(); if (!Compare(plain1, plain2)) { Console.WriteLine("CodeCoverage case failed"); return false; } return true; } } }
private static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes) { byte[] decryptedBytes = null; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { try { AES.KeySize = AESKeySize_256; AES.Key = passwordBytes; AES.Mode = AESCipherMode_ECB; AES.Padding = AESPadding_PKCS7; using (CryptoStream cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length); cs.Close(); } decryptedBytes = ms.ToArray(); } catch (CryptographicException e) { throw e; } } } return decryptedBytes; }
public static string Encrypt(string originalString, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); // 把字符串放到byte数组中 byte[] inputByteArray = Encoding.Default.GetBytes(originalString); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //原文使用ASCIIEncoding.ASCII方法的 //GetBytes方法 MemoryStream ms = new MemoryStream(); //使得输入密码必须输入英文文本 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); }
public static string Decrypt(string originalString, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[originalString.Length / 2]; for (int x = 0; x < originalString.Length / 2; x++) { int i = (Convert.ToInt32(originalString.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } //建立加密对象的密钥和偏移量,此值重要,不能修改 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象 StringBuilder ret = new StringBuilder(); return System.Text.Encoding.Default.GetString(ms.ToArray()); }
public static string Encrypt(string plainText, string passPhrase) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null)) { byte[] keyBytes = password.GetBytes(keysize / 8); using (RijndaelManaged symmetricKey = new RijndaelManaged()) { symmetricKey.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)) { using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); return Convert.ToBase64String(cipherTextBytes); } } } } } }
public static string Decrypt(string stringToDecrypt) { string sEncryptionKey = "thuynnxkey"; byte[] key = { }; byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 }; byte[] inputByteArray = new byte[stringToDecrypt.Length]; try { key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(stringToDecrypt); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (System.Exception ex) { SiAuto.Main.LogString("Lỗi :", ex.ToString()); return (string.Empty); } }
public static string Decrypt(string inName, string password) { PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, keySalt); Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); using (var fin = new FileStream(inName, FileMode.Open, FileAccess.Read)) using (var fout = new MemoryStream()) using (var cs = new CryptoStream(fout, alg.CreateDecryptor(), CryptoStreamMode.Write)) { byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = fin.Read(buffer, 0, buffer.Length); cs.Write(buffer, 0, bytesRead); } while (bytesRead != 0); cs.FlushFinalBlock(); return Encoding.ASCII.GetString(fout.ToArray()); } }
public static byte[] Encrypt(byte[] data, string password) { byte[] result = null; byte[] passwordBytes = Encoding.Default.GetBytes(password); using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = keySize; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, salt, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(data, 0, data.Length); cs.Close(); } result = ms.ToArray(); } } return result; }
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; // Set your salt here, change it to meet your flavor: // The salt bytes must be at least 8 bytes. byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; //end public byte[] AES_Encrypt }
public static string DecryptString(string input, string cryptographicProvider_PublicKey, string cryptographicProvider_IV) { try { input = input.Replace(CryptographicProviderKey, String.Empty); using (var dataString = new MemoryStream()) { var service = new TripleDESCryptoServiceProvider().CreateDecryptor(Encoding.UTF8.GetBytes(cryptographicProvider_PublicKey), Encoding.UTF8.GetBytes(cryptographicProvider_IV)); using (var cryptoStream = new CryptoStream(dataString, service, CryptoStreamMode.Write)) { var inputData = Convert.FromBase64String(input); cryptoStream.Write(inputData, 0, inputData.Length); cryptoStream.FlushFinalBlock(); var dataResult = dataString.ToArray(); var resultString = Encoding.UTF8.GetString(Convert.FromBase64String(Convert.ToBase64String(dataResult))); cryptoStream.Close(); return resultString; } } } catch (Exception e) { return e.ToString(); } }
//This method is to decrypt the password given by user. public static string Decrypt(string data, string password) { if (String.IsNullOrEmpty(data)) throw new ArgumentException("No data given"); if (String.IsNullOrEmpty(password)) throw new ArgumentException("No password given"); byte[] rawData = Convert.FromBase64String(data.Replace(" ", "+")); 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); TripleDES tdes = TripleDES.Create(); //Rijndael aes = Rijndael.Create(); tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8); tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8); // decrypt the data using (MemoryStream memoryStream = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(rawData, 8, rawData.Length - 8); cryptoStream.Close(); byte[] decrypted = memoryStream.ToArray(); return Encoding.Unicode.GetString(decrypted); } }
/// <summary> /// Encrypt some text and return an encrypted byte array. /// </summary> /// <param name="TextValue">The Text to encrypt</param> /// <returns>byte[] of the encrypted value</returns> public byte[] Encrypt(string TextValue) { //Translates our text value into a byte array. Byte[] bytes = UTFEncoder.GetBytes(TextValue); //Used to stream the data in and out of the CryptoStream. MemoryStream memoryStream = new MemoryStream(); /* * We will have to write the unencrypted bytes to the * stream, then read the encrypted result back from the * stream. */ #region Write the decrypted value to the encryption stream CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); #endregion #region Read encrypted value back out of the stream memoryStream.Position = 0; byte[] encrypted = new byte[memoryStream.Length]; memoryStream.Read(encrypted, 0, encrypted.Length); #endregion //Clean up. cs.Close(); memoryStream.Close(); return encrypted; }
private string DeCryption(string content, string sKey, string sIV) { try { byte[] inputByteArray = Convert.FromBase64String(content); using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider()) { //byte[] inputByteArray = Convert.FromBase64String(content); desProvider.Key = System.Text.Encoding.ASCII.GetBytes(sKey); desProvider.IV = System.Text.Encoding.ASCII.GetBytes(sIV); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms,desProvider.CreateDecryptor(), CryptoStreamMode.Write)) { //cs.Clear(); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = System.Text.Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return str; } } catch { return "String Not Base64 Encode!!!"; } }
// 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; }
public static string Decrypt(this string text, string lKey) { try { using (Aes aes = new AesManaged()) { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey)); aes.Key = deriveBytes.GetBytes(128 / 8); aes.IV = aes.Key; using (MemoryStream decryptionStream = new MemoryStream()) { using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) { byte[] encryptedData = Convert.FromBase64String(text); decrypt.Write(encryptedData, 0, encryptedData.Length); decrypt.Flush(); } byte[] decryptedData = decryptionStream.ToArray(); string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length); return decryptedText; } } } catch { return String.Empty; } }
public string Encrypt(string item, string password) { if (item == null) { throw new ArgumentNullException ("item"); } if (string.IsNullOrEmpty (password)) { throw new ArgumentNullException ("password"); } var des = new DESCryptoServiceProvider (); des.GenerateIV (); var rfc2898DeriveBytes = new Rfc2898DeriveBytes (password, des.IV, ITERATIONS); byte[] key = rfc2898DeriveBytes.GetBytes (8); using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, des.IV), CryptoStreamMode.Write)) { memoryStream.Write (des.IV, 0, des.IV.Length); byte[] bytes = Encoding.UTF8.GetBytes (item); cryptoStream.Write (bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock (); return Convert.ToBase64String (memoryStream.ToArray ()); } } }
//This method is to encrypt the password given by user. public static string Encrypt(string data, string password) { if (String.IsNullOrEmpty(data)) throw new ArgumentException("No data given"); if (String.IsNullOrEmpty(password)) throw new ArgumentException("No password given"); // setup the encryption algorithm Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, 8); TripleDES tdes = TripleDES.Create(); //Rijndael aes = Rijndael.Create(); tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8); tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8); // encrypt the data byte[] rawData = Encoding.Unicode.GetBytes(data); using (MemoryStream memoryStream = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateEncryptor(), CryptoStreamMode.Write)) { memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length); cryptoStream.Write(rawData, 0, rawData.Length); cryptoStream.Close(); byte[] encrypted = memoryStream.ToArray(); return Convert.ToBase64String(encrypted); } }
public static string Encrypt(this string text, string lKey) { try { using (Aes aes = new AesManaged()) { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey)); aes.Key = deriveBytes.GetBytes(128 / 8); aes.IV = aes.Key; using (MemoryStream encryptionStream = new MemoryStream()) { using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] cleanText = Encoding.UTF8.GetBytes(text); encrypt.Write(cleanText, 0, cleanText.Length); encrypt.FlushFinalBlock(); } byte[] encryptedData = encryptionStream.ToArray(); string encryptedText = Convert.ToBase64String(encryptedData); return encryptedText; } } } catch { return String.Empty; } }
public static Boolean Test() { String Text = "This is some test text"; Console.WriteLine("Original text : " + Text); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, new ToBase64Transform(), CryptoStreamMode.Write); cs.Write(Encoding.ASCII.GetBytes(Text), 0, Text.Length); cs.Close(); Console.WriteLine("Encoded : " + Encoding.ASCII.GetString(ms.ToArray())); MemoryStream ms1 = new MemoryStream(); CryptoStream cs1 = new CryptoStream(ms1, new FromBase64Transform(), CryptoStreamMode.Write); cs1.Write(ms.ToArray(), 0, (int)ms.ToArray().Length); cs1.Close(); Console.WriteLine("Decoded : " + Encoding.ASCII.GetString(ms1.ToArray())); String mod = Encoding.ASCII.GetString((Byte[])ms.ToArray().Clone()); mod = mod.Insert(17, "\n").Insert(4, " ").Insert(8,"\t"); Byte[] modified = Encoding.ASCII.GetBytes(mod); MemoryStream ms2 = new MemoryStream(); CryptoStream cs2 = new CryptoStream(ms2, new FromBase64Transform(), CryptoStreamMode.Write); cs2.Write(modified, 0, (int)modified.Length); cs2.Close(); Console.WriteLine("Decoded (with whitespaces) : " + Encoding.ASCII.GetString(ms2.ToArray())); if (!Compare(ms1.ToArray(), ms2.ToArray())) return false; return true; }
/// <summary> /// Encrypt string using AES 128 /// </summary> /// <param name="plaintext"></param> /// <param name="key"></param> /// <returns></returns> public static string Encrypt(string plaintext, string key) { byte[] keybytes = Encoding.UTF8.GetBytes(key); RijndaelManaged aes = new RijndaelManaged(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; byte[] IVbytes = Encoding.ASCII.GetBytes("dongbinhuiasxiny"); ICryptoTransform encryptor = aes.CreateEncryptor(keybytes, IVbytes); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); byte[] plainBytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(plaintext))); cs.Write(plainBytes, 0, plainBytes.Length); cs.FlushFinalBlock(); byte[] cipherBytes = ms.ToArray(); ms.Close(); cs.Close(); return Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length); }
private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV) { //Create the file streams to handle the input and output files. FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); //Create variables to help with read and write. byte[] bin = new byte[100]; //This is intermediate storage for the encryption. long rdlen = 0; //This is the total number of bytes written. long totlen = fin.Length; //This is the total length of the input file. int len; //This is the number of bytes to be written at a time. SymmetricAlgorithm des = new DESCryptoServiceProvider(); des.Padding = PaddingMode.PKCS7; CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); Console.WriteLine("Encrypting..."); //Read from the input file, then encrypt and write to the output file. while(rdlen < totlen) { len = fin.Read(bin, 0, 100); encStream.Write(bin, 0, len); rdlen = rdlen + len; Console.WriteLine("{0} bytes processed", rdlen); } encStream.Close(); }
//cmThe function used to decrypt the text private static string Decrypt(string strText, string SaltKey) { byte[] byKey = { }; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef }; byte[] inputByteArray = new byte[strText.Length + 1]; try { byKey = System.Text.Encoding.UTF8.GetBytes(SaltKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (Exception ex) { return ex.Message; } }
public static void Main() { string PlainText = "Titan"; byte[] PlainBytes = new byte[5]; PlainBytes = Encoding.ASCII.GetBytes(PlainText.ToCharArray()); PrintByteArray(PlainBytes); byte[] CipherBytes = new byte[8]; PasswordDeriveBytes pdb = new PasswordDeriveBytes("Titan", null); byte[] IV = new byte[8]; byte[] Key = pdb.CryptDeriveKey("RC2", "SHA1", 40, IV); PrintByteArray(Key); PrintByteArray(IV); // Now use the data to encrypt something RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); Console.WriteLine(rc2.Padding); Console.WriteLine(rc2.Mode); ICryptoTransform sse = rc2.CreateEncryptor(Key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs1 = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs1.Write(PlainBytes, 0, PlainBytes.Length); cs1.FlushFinalBlock(); CipherBytes = ms.ToArray(); cs1.Close(); Console.WriteLine(Encoding.ASCII.GetString(CipherBytes)); PrintByteArray(CipherBytes); ICryptoTransform ssd = rc2.CreateDecryptor(Key, IV); CryptoStream cs2 = new CryptoStream(new MemoryStream(CipherBytes), ssd, CryptoStreamMode.Read); byte[] InitialText = new byte[5]; cs2.Read(InitialText, 0, 5); Console.WriteLine(Encoding.ASCII.GetString(InitialText)); PrintByteArray(InitialText); }
/// <summary> /// ถอดรหัสข้อมูล /// </summary> /// <param name="Value">ข้อมูลที่ต้องการให้ถอดรหัส</param> /// <returns>ข้อมูลหลังจากถอดรหัส</returns> /// <example> /// clsSecurity.Decrypt("e0NDKIlUhHF3qcIdkmGpZw=="); /// </example> public string Decrypt(string Value) { #region Variable SymmetricAlgorithm mCSP; ICryptoTransform ct = null; MemoryStream ms = null; CryptoStream cs = null; byte[] byt; byte[] result; #endregion #region Procedure mCSP = new RijndaelManaged(); try { mCSP.Key = _key; mCSP.IV = _initVector; ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV); byt = Convert.FromBase64String(Value); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); result = ms.ToArray(); } catch { result = null; } finally { if (ct != null) ct.Dispose(); if (ms != null) if (ms.CanRead) { ms.Dispose(); } if (cs != null) if (cs.CanRead) { cs.Dispose(); } } try { return ASCIIEncoding.UTF8.GetString(result); } catch (Exception) { return ""; } #endregion }
protected byte[] Transform(byte[] buffer, ICryptoTransform transform) { MemoryStream stream = new MemoryStream(); using (CryptoStream cs = new CryptoStream(stream, transform, CryptoStreamMode.Write)) { cs.Write(buffer, 0, buffer.Length); } return stream.ToArray(); }
public byte[] Encrypt(byte[] cipherText) { MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write); cryptoStream.Write(cipherText, 0, (int)cipherText.Length); cryptoStream.FlushFinalBlock(); memoryStream.Close(); return memoryStream.ToArray(); }
public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV) { MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherData, 0, (int)cipherData.Length); cs.Close(); return ms.ToArray(); }
public string DecryptionDESEcb(string strText, string strKey) { string deFile = System.IO.File.ReadAllText(@"C:\Users\Lukas\Desktop\DesAlgoritmas\EncryptedText.txt"); byte[] bykey = { }; byte[] iv = { 0x01, 0x06, 0x06, 0x02, 0x09, 0x06, 0x02, 0x07 }; byte[] input = new byte[deFile.Length]; try { bykey = Encoding.UTF8.GetBytes(strKey); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Mode = CipherMode.ECB; input = Convert.FromBase64String(deFile); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(bykey, iv), CryptoStreamMode.Write); cs.Write(input, 0, input.Length); cs.FlushFinalBlock(); Encoding en = Encoding.UTF8; File.WriteAllText(@"C:\Users\Lukas\Desktop\DesAlgoritmas\DecryptedText.txt", en.GetString(ms.ToArray())); return(en.GetString(ms.ToArray())); } catch (Exception ex) { } return(null); }
/// <summary> /// AES加密 /// </summary> /// <param name="Data">被加密的明文</param> /// <param name="Key">密钥</param> /// <param name="Vector">向量</param> /// <returns>密文</returns> public static Byte[] AESEncrypt(Byte[] Data, String Key, String Vector) { Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); Byte[] bVector = new Byte[16]; Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length); Byte[] Cryptograph = null; // 加密后的密文 Rijndael Aes = Rijndael.Create(); try { // 开辟一块内存流 using (MemoryStream Memory = new MemoryStream()) { // 把内存流对象包装成加密流对象 using (CryptoStream Encryptor = new CryptoStream(Memory, Aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write)) { // 明文数据写入加密流 Encryptor.Write(Data, 0, Data.Length); Encryptor.FlushFinalBlock(); Cryptograph = Memory.ToArray(); } } } catch { Cryptograph = null; } return(Cryptograph); }
public static string Encrypt(string plainText, string password, string saltKey, string viKey) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(saltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(viKey)); byte[] cipherTextBytes; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); cryptoStream.Close(); } memoryStream.Close(); } return(Convert.ToBase64String(cipherTextBytes)); }
private string EncryptMessageForMs(string payload, bool sendsResponse = true) { using (var aes = Aes.Create()) { aes.Padding = PaddingMode.None; aes.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = aes.CreateEncryptor(_aesKey, _aesIv)) { using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(PrepareEncrypt(payload, encryptor.OutputBlockSize)); } var msFnc = "fenc"; if (!sendsResponse) { msFnc = "enc"; } return($"jdev/sys/{msFnc}/{WebUtility.UrlEncode(Convert.ToBase64String(memoryStream.ToArray()))}"); } } } }
public static byte[] Transform(ICryptoTransform transform, byte[] buffer) { byte[] buffer2 = null; using (MemoryStream stream = new MemoryStream()) { CryptoStream stream2 = null; try { stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write); stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); buffer2 = stream.ToArray(); } finally { if (stream2 != null) { stream2.Close(); stream2.Dispose(); } } } return(buffer2); }
/** * decrypts with AES 128 ECB to bytes */ public byte[] DecryptToBytes(string encryptedText) { if (string.IsNullOrEmpty(encryptedText)) { return(null); } byte[] encryptedTextAsArray = Convert.FromBase64String(encryptedText); using (Aes aes = Aes.Create()) { aes.Key = _encriptionKey; aes.Mode = CipherMode; aes.BlockSize = 128; aes.Padding = Padding; byte[] IV = new byte[aes.BlockSize / 8]; byte[] cipherText = new byte[encryptedTextAsArray.Length - IV.Length]; Array.Copy(encryptedTextAsArray, IV, IV.Length); Array.Copy(encryptedTextAsArray, IV.Length, cipherText, 0, cipherText.Length); aes.IV = IV; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write)) { cryptoStream.Write(cipherText, 0, cipherText.Length); cryptoStream.FlushFinalBlock(); return(memoryStream.ToArray()); } } } }
/// <summary> /// 解密数据 /// </summary> /// <param name="text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Decrypt(string text, string sKey) { var des = new DESCryptoServiceProvider(); var len = text.Length / 2; byte[] inputByteArray = new byte[len]; int x; for (x = 0; x < len; x++) { var i = Convert.ToInt32(text.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } var bKey = Encoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); des.Key = bKey; des.IV = bKey; System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return(Encoding.Default.GetString(ms.ToArray())); }
/// <summary> /// Encrypts using AES/CBC/PKCS7 an input byte array with a given key and IV /// </summary> public static byte[] AESEncrypt(byte[] input, byte[] key, byte[] iv) { if (input == null) { throw new ArgumentNullException(nameof(input)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (iv == null) { throw new ArgumentNullException(nameof(iv)); } using (var aes = Aes.Create()) { aes.BlockSize = 128; aes.KeySize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using (var aesTransform = aes.CreateEncryptor(key, iv)) using (var ms = new MemoryStream()) using (var cs = new CryptoStream(ms, aesTransform, CryptoStreamMode.Write)) { cs.Write(input, 0, input.Length); cs.FlushFinalBlock(); return(ms.ToArray()); } } }
/// <summary> /// Encrypts a byte array generating a byte array of cipher text. /// </summary> /// <param name="plainTextBytes"> /// Plain text bytes to be encrypted. /// </param> /// <returns> /// Cipher text formatted as a byte array. /// </returns> public byte[] EncryptToBytes(byte[] plainTextBytes) { // Add salt at the beginning of the plain text bytes (if needed). byte[] plainTextBytesWithSalt = AddSalt(plainTextBytes); // Encryption will be performed using memory stream. MemoryStream memoryStream = new MemoryStream(); // Let's make cryptographic operations thread-safe. lock (this) { // To perform encryption, we must use the Write mode. CryptoStream cryptoStream = new CryptoStream( memoryStream, encryptor, CryptoStreamMode.Write); // Start encrypting data. cryptoStream.Write(plainTextBytesWithSalt, 0, plainTextBytesWithSalt.Length); // Finish the encryption operation. cryptoStream.FlushFinalBlock(); // Move encrypted data from memory into a byte array. byte[] cipherTextBytes = memoryStream.ToArray(); // Close memory streams. memoryStream.Close(); cryptoStream.Close(); // Return encrypted data. return(cipherTextBytes); } }
public static string DesDecrypt(string pToDecrypt) { //转义特殊字符 pToDecrypt = pToDecrypt.Replace("-", "+"); pToDecrypt = pToDecrypt.Replace("_", "/"); pToDecrypt = pToDecrypt.Replace("~", "="); byte[] inputByteArray = Convert.FromBase64String(pToDecrypt); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { //des.Key = UTF8Encoding.ASCII.GetByteCount des.Key = UTF8Encoding.UTF8.GetBytes(sKey); des.IV = UTF8Encoding.UTF8.GetBytes(sKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return(str); } }
/// <summary> /// AES加密 /// </summary> /// <param name="encryptString">待加密的密文</param> /// <param name="encryptKey">加密密匙</param> /// <returns></returns> public static string AESEncrypt(string encryptString, string encryptKey) { string returnValue; byte[] temp = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ=="); Rijndael AESProvider = Rijndael.Create(); try { byte[] byteEncryptString = Encoding.Default.GetBytes(encryptString); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, AESProvider.CreateEncryptor(Encoding.Default.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); }
/// <summary> /// DES解密 /// </summary> /// <param name="decryptString">密文</param> /// <param name="decryptKey">密匙(8位)</param> /// <returns></returns> public static string DESDecrypt(string decryptString, string decryptKey) { string returnValue; try { byte[] temp = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; DESCryptoServiceProvider dES = new DESCryptoServiceProvider(); byte[] byteDecryptString = Convert.FromBase64String(decryptString); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, dES.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), temp), CryptoStreamMode.Write); cryptoStream.Write(byteDecryptString, 0, byteDecryptString.Length); cryptoStream.FlushFinalBlock(); returnValue = Encoding.Default.GetString(memoryStream.ToArray()); } catch (Exception ex) { throw ex; } return(returnValue); }
/// <summary> /// 암호화 한다. /// </summary> /// <param name="_strSouceString"></param> /// <returns></returns> public string Encrypting(string _strSouceString) { byte[] bytSource; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { ICryptoTransform encrypto = _tdes.CreateEncryptor(); CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); bytSource = encoding.GetBytes(_strSouceString); //if (encoding_codename == null) // bytSource = Encoding.Default.GetBytes(_strSouceString); //Convert.FromBase64String(_strSouceString); //encoding.GetBytes(_strSouceString); //else // bytSource = Encoding.GetEncoding(encoding_codename).GetBytes(_strSouceString); cs.Write(bytSource, 0, bytSource.Length); cs.FlushFinalBlock(); return(Convert.ToBase64String(ms.ToArray())); //return encoding.GetString(ms.ToArray()); } }
/// <summary> /// DES加密 /// </summary> /// <param name="Text">加密内容</param> /// <param name="sKey">Key</param> /// <returns></returns> public static string Encrypt(string Text, string sKey) { DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider(); byte[] bytes = Encoding.Default.GetBytes(Text); MD5 mD = MD5.Create(); dESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes(BitConverter.ToString(mD.ComputeHash(Encoding.Default.GetBytes(sKey))).Replace("-", null).Substring(0, 8)); dESCryptoServiceProvider.IV = Encoding.ASCII.GetBytes(BitConverter.ToString(mD.ComputeHash(Encoding.Default.GetBytes(sKey))).Replace("-", null).Substring(0, 8)); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(), CryptoStreamMode.Write); cryptoStream.Write(bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock(); StringBuilder stringBuilder = new StringBuilder(); byte[] array = memoryStream.ToArray(); for (int i = 0; i < array.Length; i++) { byte b = array[i]; stringBuilder.AppendFormat("{0:X2}", b); } return(stringBuilder.ToString()); }
public static byte[] DecryptFile(byte[] bytesToBeDecrypted, byte[] passwordBytes) { byte[] decryptedBytes; using (var ms = new MemoryStream()) { using (var aes = new RijndaelManaged()) { aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using ( var cs = new CryptoStream(ms, aes.CreateDecryptor(passwordBytes, passwordBytes), CryptoStreamMode.Write)) { cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length); cs.Close(); } decryptedBytes = ms.ToArray(); } } return(decryptedBytes); }
public string EncryptString(string inputString) { MemoryStream memStream = null; try { byte[] key = { }; byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 }; string encryptKey = "aXb2uy4z"; // MUST be 8 characters key = Encoding.UTF8.GetBytes(encryptKey); byte[] byteInput = Encoding.UTF8.GetBytes(inputString); DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); memStream = new MemoryStream(); ICryptoTransform transform = provider.CreateEncryptor(key, IV); CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write); cryptoStream.Write(byteInput, 0, byteInput.Length); cryptoStream.FlushFinalBlock(); } catch (Exception ex) { throw new Exception(ex.Message); } return(Convert.ToBase64String(memStream.ToArray())); }
public static string DES_Decode(string source, string sKey) { if (sKey == "" || sKey == null) { sKey = "12345678"; } byte[] inputByteArray = System.Convert.FromBase64String(source);//Encoding.UTF8.GetBytes(source); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return(str); } }
/// <summary> /// 암호화 풀기 /// </summary> /// <param name="plainText"></param> /// <returns></returns> public string GetDeCryptString(string plainText) { Debug.Assert(null != AESKEY); Debug.Assert(null != AESIV); Debug.Assert(false == string.IsNullOrEmpty(plainText)); RijndaelManaged aes = new RijndaelManaged { KeySize = 256, BlockSize = 128, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, Key = AESKEY, IV = AESIV }; var decrypt = aes.CreateDecryptor(); byte[] xBuff = null; using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write)) { byte[] xXml = Convert.FromBase64String(plainText); cs.Write(xXml, 0, xXml.Length); } xBuff = ms.ToArray(); } string Output = Encoding.UTF8.GetString(xBuff); return(Output); }
public static string Decrypt(string cipherText, string EncryptionKey) { try { cipherText = cipherText.Replace(" ", "+"); byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } Console.WriteLine(cipherText); return(cipherText); } catch (Exception e) { string message = "Wrong Password"; return(message); } }
public string Decrypt(byte[] encryptedMessage, byte[] iv, byte[] key) { string message; using (Aes aes = new AesCryptoServiceProvider()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Key = key; aes.IV = iv; // Decrypt the message using (MemoryStream plaintext = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(plaintext, aes.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(encryptedMessage, 0, encryptedMessage.Length); cs.Close(); message = Encoding.UTF8.GetString(plaintext.ToArray()); } } } return(message); }
public static string Encrypt(string textToEncrypt) { try { var toReturn = ""; var ivByte = Encoding.UTF8.GetBytes(Resources.TextEncryptIV.Substring(0, 8)); var keyByte = Encoding.UTF8.GetBytes(Resources.TextEncryptKey.Substring(0, 8)); var inputByteArray = Encoding.UTF8.GetBytes(textToEncrypt); using (var des = new DESCryptoServiceProvider()) { var ms = new MemoryStream(); var cs = new CryptoStream(ms, des.CreateEncryptor(keyByte, ivByte), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); toReturn = Convert.ToBase64String(ms.ToArray()); } return(toReturn); } catch (Exception ae) { throw new Exception(ae.Message, ae.InnerException); } }
/// <summary> /// Encrypts the byte array. /// </summary> public static byte[] EncryptBytes(byte[] bytes, byte[] secretKey, byte[] iv) { RijndaelManaged alg = null; try { alg = new RijndaelManaged() { Key = secretKey, IV = iv }; using (MemoryStream memStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memStream, alg.CreateEncryptor(secretKey, iv), CryptoStreamMode.Write)) { cryptoStream.Write(bytes, 0, bytes.Length); } return memStream.ToArray(); } } finally { alg?.Clear(); } }
/// <summary> /// 加密 /// </summary> /// <param name="pToEncrypt"></param> /// <returns></returns> public string Encrypt(string pToEncrypt) { if (string.IsNullOrEmpty(pToEncrypt)) { return(string.Empty); } DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //把字符串放到byte数组中 //原来使用的UTF8编码,我改成Unicode编码了,不行 byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); //建立加密对象的密钥和偏移量 //使得输入密码必须输入英文文本 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(pv); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return(BitConverter.ToString(ms.ToArray()).Replace("-", "")); }
private static string _Decrypt(string cipherText, Keys objKey) { var cipherBytes = Convert.FromBase64String(cipherText.Trim()); using (var encryptor = Aes.Create()) { if (encryptor == null) { return(cipherText); } var pdb = new Rfc2898DeriveBytes(objKey.KeyCode, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } return(cipherText.Trim()); }
/// <summary> /// Encrypts the specified algorithm. /// The type of algorithm is SymmetricAlgorithm, so the Encrypt /// supports all kind of Symmetric Algorithm (cf: DES, TripleDes etc). /// </summary> /// /// <param name="algorithm">The algorithm.</param> /// <param name="plainText">The plain text.</param> /// <param name="key">The key.</param> /// <param name="cipherMode">The cipher mode.</param> /// <param name="paddingMode">The padding mode.</param> /// <returns> The string base on base64. </returns> public static string Encrypt(SymmetricAlgorithm algorithm, string plainText, byte[] key, CipherMode cipherMode, PaddingMode paddingMode) { byte[] plainBytes; byte[] cipherBytes; algorithm.Key = key; algorithm.Mode = cipherMode; algorithm.Padding = paddingMode; BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { bf.Serialize(stream, plainText); plainBytes = stream.ToArray(); } using (MemoryStream ms = new MemoryStream()) { // Defines a stream for cryptographic transformations CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write); // Writes a sequence of bytes for encrption cs.Write(plainBytes, 0, plainBytes.Length); // Closes the current stream and releases any resources cs.Close(); // Save the ciphered message into one byte array cipherBytes = ms.ToArray(); // Closes the memorystream object ms.Close(); } string base64Text = Convert.ToBase64String(cipherBytes); return(base64Text); }
public static string Encrypt(string encryptString) { string EncryptionKey = "0ram@1234xxxxxxxxxxtttttuuuuuiiiiio"; byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); } encryptString = Convert.ToBase64String(ms.ToArray()); } } return(encryptString); }
static byte[] Decrypt(byte[] value, byte[] password) { byte[] Decrypt = null; var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (MemoryStream memoryStream = new MemoryStream()) { using (RijndaelManaged rijndaelManaged = new RijndaelManaged { KeySize = 256, BlockSize = 128, Mode = CipherMode.CBC }) { Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, 1000); rijndaelManaged.Key = rfc2898DeriveBytes.GetBytes(rijndaelManaged.KeySize / 8); rijndaelManaged.IV = rfc2898DeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8); using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(value, 0, value.Length); cryptoStream.Close(); } Decrypt = memoryStream.ToArray(); } } return(Decrypt); }
/// <summary> /// 加密方法 /// </summary> /// <param name="Source">待加密的串</param> /// <returns>经过加密的串</returns> public static string Encrypto(string Source) { if (Key.Length != KeySize) { return(""); } //if (Source.Length <= KeyPostion) // Source += Key; //else // Source.Insert(KeyPostion, Key); byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source); MemoryStream ms = new MemoryStream(); mobjCryptoService.Key = GetLegalKey(Key); mobjCryptoService.IV = GetLegalIV(); ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); ms.Close(); byte[] bytOut = ms.ToArray(); string encryStr = Convert.ToBase64String(bytOut); //200字节处放32位密码 if (encryStr.Length <= KeyPostion) { encryStr += Key; } else { encryStr = encryStr.Insert(KeyPostion, Key); } return(encryStr); }
/// <summary> /// DES解密字符串 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string Decrypt(string decryptString, string decryptKey = "12345678") { if (string.IsNullOrEmpty(decryptString)) { return(string.Empty); } try { byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return(Encoding.UTF8.GetString(mStream.ToArray())); } catch { return(decryptString); } }
public static string Encrypt(string sourceString) { byte[] btKey = Encoding.UTF8.GetBytes(sKey); byte[] btIV = Encoding.UTF8.GetBytes(sKey); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); using (MemoryStream ms = new MemoryStream()) { byte[] inData = Encoding.UTF8.GetBytes(sourceString); try { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write)) { cs.Write(inData, 0, inData.Length); cs.FlushFinalBlock(); } return(Convert.ToBase64String(ms.ToArray())); } catch { throw; } } }
public static string EncryptRijndael(string original) { byte[] encrypted; byte[] toEncrypt; UTF8Encoding utf8Converter = new UTF8Encoding(); toEncrypt = utf8Converter.GetBytes(original); RijndaelManaged myRijndael = new RijndaelManaged(); MemoryStream ms = new MemoryStream(); ICryptoTransform encryptor = myRijndael.CreateEncryptor(Key, IV); CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(toEncrypt, 0, toEncrypt.Length); cs.FlushFinalBlock(); encrypted = ms.ToArray(); string encryptedString = Convert.ToBase64String(encrypted); return encryptedString; }
public static string Decrypt(string cipherText) { try { string EncryptionKey = "MAKV2SPBNI99212"; cipherText = cipherText.Replace(" ", "+"); byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } return cipherText; } catch (Exception ex) { return "0"; } }