2013-07-09 100 views
1

我正在嘗試從文件nad中讀取文本並對其進行加密並將其傳遞給字符串格式的函數。 後來我也想解密它。c#.net中的簡單加密算法.net

我試過以下,但它沒有做任何加密。任何人都可以提出任何簡單的加密算法?

fileStream = store.OpenFile(strFilePath, FileMode.Open, FileAccess.Read); 
strEncryptedFileStream = Encoding.Unicode.GetBytes(fileStream.ToString()).ToString(); 
+0

你認爲哪一個代碼會做你貼什麼加密的答案嗎? –

+1

選中此項:http://stackoverflow.com/questions/165808/simple-2-way-encryption-for-c-sharp –

+0

你所做的基本上是從整個文件中獲取字符串的Unicode字節數組 –

回答

8

使用AES。這是一個輔助類。沒有意義使用「簡單」,或換句話說,容易破解加密。要麼人們能夠打破它,要麼你不能。選擇一個衆所周知的測試加密標準。

如果不滿足您的需求,您可以根據需要修改以下示例。

using System; 
using System.IO; 
using System.Security.Cryptography; 
using System.Text; 
using System.Diagnostics; 

namespace Common.Cryptography 
{ 
    /// <summary> 
    /// AES is a symmetric 256-bit encryption algorthm. 
    /// Read more: http://en.wikipedia.org/wiki/Advanced_Encryption_Standard 
    /// </summary> 
    public static class AES 
    { 
     private const string _SALT = "g46dzQ80"; 
     private const string _INITVECTOR = "OFRna74m*aze01xY"; 

     private static byte[] _saltBytes; 
     private static byte[] _initVectorBytes; 

     static AES() 
     { 
      _saltBytes = Encoding.UTF8.GetBytes(_SALT); 
      _initVectorBytes = Encoding.UTF8.GetBytes(_INITVECTOR); 
     } 


     /// <summary> 
     /// Encrypts a string with AES 
     /// </summary> 
     /// <param name="plainText">Text to be encrypted</param> 
     /// <param name="password">Password to encrypt with</param> 
     /// <param name="salt">Salt to encrypt with</param>  
     /// <param name="initialVector">Needs to be 16 ASCII characters long</param>  
     /// <returns>An encrypted string</returns>   
     public static string Encrypt(string plainText, string password, string salt = null, string initialVector = null) 
     { 
      return Convert.ToBase64String(EncryptToBytes(plainText, password, salt, initialVector)); 
     } 

     /// <summary> 
     /// Encrypts a string with AES 
     /// </summary> 
     /// <param name="plainText">Text to be encrypted</param> 
     /// <param name="password">Password to encrypt with</param> 
     /// <param name="salt">Salt to encrypt with</param>  
     /// <param name="initialVector">Needs to be 16 ASCII characters long</param>  
     /// <returns>An encrypted string</returns>   
     public static byte[] EncryptToBytes(string plainText, string password, string salt = null, string initialVector = null) 
     { 
      byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); 
      return EncryptToBytes(plainTextBytes, password, salt, initialVector); 
     } 

     /// <summary> 
     /// Encrypts a string with AES 
     /// </summary> 
     /// <param name="plainTextBytes">Bytes to be encrypted</param> 
     /// <param name="password">Password to encrypt with</param> 
     /// <param name="salt">Salt to encrypt with</param>  
     /// <param name="initialVector">Needs to be 16 ASCII characters long</param>  
     /// <returns>An encrypted string</returns>   
     public static byte[] EncryptToBytes(byte[] plainTextBytes, string password, string salt = null, string initialVector = null) 
     { 
      int keySize = 256; 

      byte[] initialVectorBytes = string.IsNullOrEmpty(initialVector) ? _initVectorBytes : Encoding.UTF8.GetBytes(initialVector); 
      byte[] saltValueBytes = string.IsNullOrEmpty(salt) ? _saltBytes : Encoding.UTF8.GetBytes(salt); 
      byte[] keyBytes = new Rfc2898DeriveBytes(password, saltValueBytes).GetBytes(keySize/8); 

      using (RijndaelManaged symmetricKey = new RijndaelManaged()) 
      { 
       symmetricKey.Mode = CipherMode.CBC; 

       using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes)) 
       { 
        using (MemoryStream memStream = new MemoryStream()) 
        { 
         using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write)) 
         { 
          cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); 
          cryptoStream.FlushFinalBlock(); 

          return memStream.ToArray(); 
         } 
        } 
       } 
      } 
     } 

     /// <summary> 
     /// Decrypts an AES-encrypted string. 
     /// </summary> 
     /// <param name="cipherText">Text to be decrypted</param> 
     /// <param name="password">Password to decrypt with</param> 
     /// <param name="salt">Salt to decrypt with</param> 
     /// <param name="initialVector">Needs to be 16 ASCII characters long</param> 
     /// <returns>A decrypted string</returns> 
     public static string Decrypt(string cipherText, string password, string salt = null, string initialVector = null) 
     { 
      byte[] cipherTextBytes = Convert.FromBase64String(cipherText.Replace(' ','+')); 
      return Decrypt(cipherTextBytes, password, salt, initialVector).TrimEnd('\0'); 
     } 

     /// <summary> 
     /// Decrypts an AES-encrypted string. 
     /// </summary> 
     /// <param name="cipherText">Text to be decrypted</param> 
     /// <param name="password">Password to decrypt with</param> 
     /// <param name="salt">Salt to decrypt with</param> 
     /// <param name="initialVector">Needs to be 16 ASCII characters long</param> 
     /// <returns>A decrypted string</returns> 
     public static string Decrypt(byte[] cipherTextBytes, string password, string salt = null, string initialVector = null) 
     { 
      int keySize = 256; 

      byte[] initialVectorBytes = string.IsNullOrEmpty(initialVector) ? _initVectorBytes : Encoding.UTF8.GetBytes(initialVector); 
      byte[] saltValueBytes = string.IsNullOrEmpty(salt) ? _saltBytes : Encoding.UTF8.GetBytes(salt); 
      byte[] keyBytes = new Rfc2898DeriveBytes(password, saltValueBytes).GetBytes(keySize/8); 
      byte[] plainTextBytes = new byte[cipherTextBytes.Length]; 

      using (RijndaelManaged symmetricKey = new RijndaelManaged()) 
      { 
       symmetricKey.Mode = CipherMode.CBC; 

       using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes)) 
       { 
        using (MemoryStream memStream = new MemoryStream(cipherTextBytes)) 
        { 
         using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read)) 
         { 
          int byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); 

          return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount); 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+0

我該如何解密另一種語言的這種字符串,例如PHP? – Black

+1

如果您使用相同的鹽,初始向量(iv)和鍵值,則AES *的所有正確實現應能夠交換加密和解密,而不管語言如何。也就是說,並非所有的語言都以相同的方式實現了這一點。 PHP與openssl_encrypt從密鑰中剝離鹽。它看起來像這個庫試圖實現加密跨多種語言,但並不是所有的都很好拋光:https://github.com/RNCryptor – smdrager

+0

謝謝,男人!你救了我的屁股...... XDD幹得好! – firestoke

0

代碼中沒有任何內容沒有加密。你只是把它轉換成Unicode。

你可以看看this question,它給出了C#中加密的一個很好的例子。

0

Enconding方法涉及文本編碼(UTF-8,ANSI等),您應該使用加密算法,有幾種方法可以做到這一點,一個簡單的例子就是使用XOR加密。

看到這個:

string XorEncryptDecryptText(string stringText, string stringKey){ 
// Variable that receives the result of processode encryption. 
string stringNewText = &quot;&quot;; 
// First we take the difference in size of the two strings. 
int diff = (stringText.Length - stringKey.Length); 
// If the size difference that we put stringKey with the same size as the XOR stringText that no errors occur. 
if (diff &gt; 0){ 
    // We calculate the rest and the amount of times we repeat the stringKey to equal sizes. 
    int cont = (int)diff/stringKey.Length; 
    int resto = diff % stringKey.Length; 
    string stringKeyAux = stringKey; 
    // At this point the stringText concatenate the stringKey to be equal sizes. 
    for (int i = 0; i &lt; cont; i++){ 
     stringKeyAux += stringKey; 
    } 

    for (int i = 0; (i &lt; resto); i++){ 
     stringKeyAux += stringKey[i]; 
    } 
    stringKey = stringKeyAux; 
} 
// At this point piece of code is done the process of XOR. 
for (int i = 0; i &lt; stringText.Length; i++){ 
    int charValue = Convert.ToInt32(stringText[i]); 
    int charKey = Convert.ToInt32(stringKey[i]); 
    charValue ^= charKey; 
    stringNewText += char.ConvertFromUtf32(charValue); 
} 
return stringNewText;} 

string XOREncriptDecriptFile(string FileName, string stringKey){ 
string stringAux = System.IO.File.ReadAllLines(FileName); 
return XorEncryptDecryptText(stringAux, stringKey);} 

這個代碼是基於http://julioborges.p.ht/?p=769

更多的安全使用smdrager