Ergebnis 1 bis 6 von 6
  1. #1
    Mitglied
    Registriert seit
    Jun 2011
    Beiträge
    21

    Exclamation [C#] Programm zum Ver- und Entschlüsseln von Dateien

    Hi!

    Ich wollte für eine Freund ein kleines Programm machen, welches Daten mit unterschiedlicher Wichtigkeit mit unterschiedlichen Keys verschlüsselt. Zeitweise sollen auch Freunde wie ich Zugriff auf Daten bekommen. Dazu verschickt er die Keys einfach per Mail. Ich nutze das Data Encryption Standard von System.Security.Cryptography.

    Code zum Erstellen von 10 Schlüsseln, welcher prima klappt:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Security.Cryptography;
    using System.Windows.Forms;
    
    namespace Schlüssel
    {
        class Program
        {
            [STAThread]static void Main(string[] args)
            {
                string path = "";
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.Description = "Bitte wählen Sie eine Ordner zum Speichern der generierten *.key - Daten aus.";
                fbd.ShowNewFolderButton = false;
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    path = fbd.SelectedPath;
                }
                DESCryptoServiceProvider des = null;
                for (int i = 0; i != 11; i++)
                {
                    des = new DESCryptoServiceProvider();
                    System.IO.File.WriteAllBytes(path + "\\Key_" + i.ToString() + ".key", des.Key);
                    des = null;
                    Console.WriteLine(i.ToString() + ". Sicherheitsklasse wurde generiert.");
                }
                Console.WriteLine("Erfolgreich!");
                Console.ReadLine();
            }
        }
    }
    Hier der Code zum Verschlüsseln:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Security.Cryptography;
    
    
    namespace Verschlüsselung
    {
        class Program
        {
            
            [STAThread]static void Main(string[] args)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                OpenFileDialog opf1 = new OpenFileDialog();
                opf1.Filter = "Key - Dateien(*.key)|*.key";
                opf1.Multiselect = false;
                opf1.Title = "Bitte wählen Sie den Key zum Verschlüsseln aus:";
                if (opf1.ShowDialog() == DialogResult.OK)
                {
                    des.Key = File.ReadAllBytes(opf1.FileName);
                    OpenFileDialog opf2 = new OpenFileDialog();
                    opf2.Multiselect = false;
                    opf2.Title = "Bitte wählen Sie die Datei zum Verschlüsseln aus:";
                    opf2.Filter = "Alle Dateien(*.*)|*.*";
                    if (opf2.ShowDialog() == DialogResult.OK)
                    {
                        string s = opf1.SafeFileName.Remove(0,4);
                        ICryptoTransform descry = des.CreateEncryptor();
                        FileStream fs = new FileStream(opf2.FileName + "." + s + ".leocrypt", FileMode.Create, FileAccess.Write);
                        CryptoStream cryptostrm = new CryptoStream(fs, descry, CryptoStreamMode.Write);
                        cryptostrm.Write(File.ReadAllBytes(opf2.FileName), 0, File.ReadAllBytes(opf2.FileName).Length);
                        cryptostrm.Close();
                        Console.WriteLine("Erfolgreich!");
                    }
                }
                Console.ReadLine();
            }
        }
    }
    Und hier der Code zum Entschlüsseln:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Security.Cryptography;
    
    namespace Entschlüsseln
    {
        class Program
        {
            [STAThread]
            static void Main(string[] args)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                OpenFileDialog opf1 = new OpenFileDialog();
                opf1.Filter = "Key - Dateien(*.key)|*.key";
                opf1.Multiselect = false;
                opf1.Title = "Bitte wählen Sie den Key zum Entschlüsseln aus:";
                if (opf1.ShowDialog() == DialogResult.OK)
                {
                    des.Key = File.ReadAllBytes(opf1.FileName);
                    OpenFileDialog opf2 = new OpenFileDialog();
                    opf2.Multiselect = false;
                    opf2.Title = "Bitte wählen Sie die Datei zum Verschlüsseln aus:";
                    opf2.Filter = "Alle Dateien(*.*)|*.*";
                    if (opf2.ShowDialog() == DialogResult.OK)
                    {
                        FileStream fs = null;
                        string s = opf1.SafeFileName.Remove(0, 4);
                        ICryptoTransform descry = des.CreateDecryptor();
                        // Ist nicht s == 10.key
                        if (s.Length == 5)
                        {
                            fs = new FileStream(opf2.FileName.Remove(opf2.FileName.Length - 15), FileMode.Create, FileAccess.Write);
                        }
                        else 
                        {
                            fs = new FileStream(opf2.FileName.Remove(opf2.FileName.Length - 16), FileMode.Create, FileAccess.Write);
                        }
                        CryptoStream cryptostrm = new CryptoStream(fs, descry, CryptoStreamMode.Write);
                        cryptostrm.Write(File.ReadAllBytes(opf2.FileName), 0, File.ReadAllBytes(opf2.FileName).Length);
                        cryptostrm.Close();
                        Console.WriteLine("Erfolgreich!");
                    }
                }
                Console.ReadLine();
            }
        }
    }
    Alle Codes gehen ohne Fehler durch den Compiler, aber bei einer Bilddatei, die erst verschlüsselt und dann entschlüsselt wurde, kommt in der Fotoanzeige etwas von wegen : "Ungültiges Bild". Bei einer txt - Datei klappts auch prima, nur das am Ende so was rauskommt:

    Original - Text:

    Hier ist ein kleiner Text.
    Text, der rauskommt:

    žKÞéÒÎeŠ ein kleiner Text.
    Weiß vielleicht jemand meinen Fehler??

    Wäre euch sehr Dankbar.

    LeoFSU

  2. #2
    Mitglied
    Registriert seit
    Jun 2010
    Ort
    Australia
    Beiträge
    223

    Standard Re: [C#] Programm zum Ver- und Entschlüsseln von Dateien

    war jetzt zu faul mir das genau anzuschauen udn oder zu compilen udn weiss auch nicht wieso du bei den filestreams -15 bzw -16 machst ?!?!

    aufjedenfall siehts danach aus als ob du irgendwo die laenge des "arrays" nicht auf die laenge des inhalts der datei setzt sodass nur ein teil eingelesen wird etc.


    Benutz und schreib einfach meine klasse um:
    PHP-Code:
     /// <summary>
        /// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and 
        /// decrypt data. As long as encryption and decryption routines use the same
        /// parameters to generate the keys, the keys are guaranteed to be the same.
        /// The class uses static functions with duplicate code to make it easier to
        /// demonstrate encryption and decryption logic. In a real-life application, 
        /// this may not be the most efficient way of handling encryption, so - as
        /// soon as you feel comfortable with it - you may want to redesign this class.
        /// </summary>
        
    public class Cryptor
        
    {
            private static 
    KeySize KeySize getset; }
            private static 
    Algorithm Algorithm getset; }
            private static 
    int Iterations getset; }
            private static 
    string Phrase getset; }
            private static 
    string Salt getset; }

            private static 
    string _vector;

            private static 
    string Vector
            
    {
                
    get { return _vector; }
                
    set _vector AdjustLength(value); }
            }

            private static 
    string AdjustLength(string value)
            {
                for (
    int i 0value.Length 16i++)
                  
    value=  value.Insert(value.Lengthvalue[i].ToString());

                if(
    value.Length>16)
               
    valuevalue.Remove(16);
                return 
    value;
            }


            static 
    Cryptor()
            {
                
    Phrase Assembly.GetCallingAssembly().FullName;
                
    Salt Vector Assembly.GetCallingAssembly().GetHashCode().ToString();
                
    Iterations 2;
                
    Algorithm Algorithm.SHA1;
                
    KeySize KeySize.Strength256;
            }


          

            
    /// <summary>
            /// Encrypts specified plaintext using Rijndael symmetric key algorithm
            /// and returns a base64-encoded result.
            /// </summary>
            /// <param name="plainText">
            /// Plaintext value to be encrypted.
            /// </param>
            /// <param name="passPhrase">
            /// Passphrase from which a pseudo-random password will be derived. The
            /// derived password will be used to generate the encryption key.
            /// Passphrase can be any string. In this example we assume that this
            /// passphrase is an ASCII string.
            /// </param>
            /// <param name="saltValue">
            /// Salt value used along with passphrase to generate password. Salt can
            /// be any string. In this example we assume that salt is an ASCII string.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Hash algorithm used to generate password. Allowed values are: "MD5" and
            /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
            /// </param>
            /// <param name="passwordIterations">
            /// Number of iterations used to generate password. One or two iterations
            /// should be enough.
            /// </param>
            /// <param name="initVector">
            /// Initialization vector (or IV). This value is required to encrypt the
            /// first block of plaintext data. For RijndaelManaged class IV must be 
            /// exactly 16 ASCII characters long.
            /// </param>
            /// <param name="keySize">
            /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. 
            /// Longer keys are more secure than shorter keys.
            /// </param>
            /// <returns>
            /// Encrypted value formatted as a base64-encoded string.
            /// </returns>
            
    public static string Encrypt(string plainText,
                                         
    string passPhrase,
                                         
    string saltValue,
                                         
    Algorithm hashAlgorithm,
                                         
    int passwordIterations,
                                         
    string initVector,
                                         
    KeySize keySize)
            {
                
    // Convert strings into byte arrays.
                // Let us assume that strings only contain ASCII codes.
                // If strings include Unicode characters, use Unicode, UTF7, or UTF8 
                // encoding.
                
    byte[] initVectorBytes Encoding.ASCII.GetBytes(initVector);
                
    byte[] saltValueBytes Encoding.ASCII.GetBytes(saltValue);

                
    // Convert our plaintext into a byte array.
                // Let us assume that plaintext contains UTF8-encoded characters.
                
    byte[] plainTextBytes Encoding.UTF8.GetBytes(plainText);

                
    // First, we must create a password, from which the key will be derived.
                // This password will be generated from the specified passphrase and 
                // salt value. The password will be created using the specified hash 
                // algorithm. Password creation can be done in several iterations.
                
    var password = new PasswordDeriveBytes(
                    
    passPhrase,
                    
    saltValueBytes,
                    
    hashAlgorithm.ToString(),
                    
    passwordIterations);

                
    // Use the password to generate pseudo-random bytes for the encryption
                // key. Specify the size of the key in bytes (instead of bits).
                
    byte[] keyBytes password.GetBytes(((int)keySize)/8);


                
    // Create uninitialized Rijndael encryption object.
                
    var symmetricKey = new RijndaelManaged {Mode CipherMode.CBC};

                
    // It is reasonable to set encryption mode to Cipher Block Chaining
                // (CBC). Use default options for other symmetric key parameters.

                // Generate encryptor from the existing key bytes and initialization 
                // vector. Key size will be defined based on the number of the key 
                // bytes.
                
    ICryptoTransform encryptor symmetricKey.CreateEncryptor(
                    
    keyBytes,
                    
    initVectorBytes);

                
    // Define memory stream which will be used to hold encrypted data.
                
    var memoryStream = new MemoryStream();

                
    // Define cryptographic stream (always use Write mode for encryption).
                
    var cryptoStream = new CryptoStream(memoryStream,
                                                    
    encryptor,
                                                    
    CryptoStreamMode.Write);
                
    // Start encrypting.
                
    cryptoStream.Write(plainTextBytes0plainTextBytes.Length);

                
    // Finish encrypting.
                
    cryptoStream.FlushFinalBlock();

                
    // Convert our encrypted data from a memory stream into a byte array.
                
    byte[] cipherTextBytes memoryStream.ToArray();

                
    // Close both streams.
                
    memoryStream.Close();
                
    cryptoStream.Close();

                
    // Convert encrypted data into a base64-encoded string.
                
    string cipherText System.Convert.ToBase64String(cipherTextBytes);

                
    // Return encrypted string.
                
    return cipherText;
            }

            
    /// <summary>
            /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
            /// </summary>
            /// <param name="cipherText">
            /// Base64-formatted ciphertext value.
            /// </param>
            /// <param name="passPhrase">
            /// Passphrase from which a pseudo-random password will be derived. The
            /// derived password will be used to generate the encryption key.
            /// Passphrase can be any string. In this example we assume that this
            /// passphrase is an ASCII string.
            /// </param>
            /// <param name="saltValue">
            /// Salt value used along with passphrase to generate password. Salt can
            /// be any string. In this example we assume that salt is an ASCII string.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Hash algorithm used to generate password. Allowed values are: "MD5" and
            /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
            /// </param>
            /// <param name="passwordIterations">
            /// Number of iterations used to generate password. One or two iterations
            /// should be enough.
            /// </param>
            /// <param name="initVector">
            /// Initialization vector (or IV). This value is required to encrypt the
            /// first block of plaintext data. For RijndaelManaged class IV must be
            /// exactly 16 ASCII characters long.
            /// </param>
            /// <param name="keySize">
            /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
            /// Longer keys are more secure than shorter keys.
            /// </param>
            /// <returns>
            /// Decrypted string value.
            /// </returns>
            /// <remarks>
            /// Most of the logic in this function is similar to the Encrypt
            /// logic. In order for decryption to work, all parameters of this function
            /// - except cipherText value - must match the corresponding parameters of
            /// the Encrypt function which was called to generate the
            /// ciphertext.
            /// </remarks>
            
    public static string Decrypt(string cipherText,
                                         
    string passPhrase,
                                         
    string saltValue,
                                         
    Algorithm hashAlgorithm,
                                         
    int passwordIterations,
                                         
    string initVector,
                                         
    KeySize keySize)
            {
                
    // Convert strings defining encryption key characteristics into byte
                // arrays. Let us assume that strings only contain ASCII codes.
                // If strings include Unicode characters, use Unicode, UTF7, or UTF8
                // encoding.
                
    byte[] initVectorBytes Encoding.ASCII.GetBytes(initVector);
                
    byte[] saltValueBytes Encoding.ASCII.GetBytes(saltValue);

                
    // Convert our ciphertext into a byte array.
                
    byte[] cipherTextBytes System.Convert.FromBase64String(cipherText);

                
    // First, we must create a password, from which the key will be 
                // derived. This password will be generated from the specified 
                // passphrase and salt value. The password will be created using
                // the specified hash algorithm. Password creation can be done in
                // several iterations.
                
    var password = new PasswordDeriveBytes(
                    
    passPhrase,
                    
    saltValueBytes,
                    
    hashAlgorithm.ToString(),
                    
    passwordIterations);

                
    // Use the password to generate pseudo-random bytes for the encryption
                // key. Specify the size of the key in bytes (instead of bits).
                
    byte[] keyBytes password.GetBytes(((int)keySize)/8);

                
    // Create uninitialized Rijndael encryption object.
                
    var symmetricKey = new RijndaelManaged {Mode CipherMode.CBC};

                
    // It is reasonable to set encryption mode to Cipher Block Chaining
                // (CBC). Use default options for other symmetric key parameters.

                // Generate decryptor from the existing key bytes and initialization 
                // vector. Key size will be defined based on the number of the key 
                // bytes.
                
    ICryptoTransform decryptor symmetricKey.CreateDecryptor(
                    
    keyBytes,
                    
    initVectorBytes);

                
    // Define memory stream which will be used to hold encrypted data.
                
    var memoryStream = new MemoryStream(cipherTextBytes);

                
    // Define cryptographic stream (always use Read mode for encryption).
                
    var cryptoStream = new CryptoStream(memoryStream,
                                                    
    decryptor,
                                                    
    CryptoStreamMode.Read);

                
    // Since at this point we don't know what the size of decrypted data
                // will be, allocate the buffer long enough to hold ciphertext;
                // plaintext is never longer than ciphertext.
                
    var plainTextBytes = new byte[cipherTextBytes.Length];

                
    // Start decrypting.
                
    int decryptedByteCount cryptoStream.Read(plainTextBytes,
                                                           
    0,
                                                           
    plainTextBytes.Length);

                
    // Close both streams.
                
    memoryStream.Close();
                
    cryptoStream.Close();

                
    // Convert decrypted data into a string. 
                // Let us assume that the original plaintext string was UTF8-encoded.
                
    string plainText Encoding.UTF8.GetString(plainTextBytes,
                                                           
    0,
                                                           
    decryptedByteCount);

                
    // Return decrypted string.   
                
    return plainText;
            }

           
    /// <summary>
           /// 
           /// </summary>
           /// <param name="obj"></param>
           /// <returns></returns>
            
    public static string Decrypt(object obj)
            {
                return 
    Decrypt(obj.ToString(), PhraseSaltAlgorithmIterationsVectorKeySize);
            
            }

           
    /// <summary>
           /// 
           /// </summary>
           /// <param name="obj"></param>
           /// <returns></returns>
            
    public static string Encrypt(object obj)
            {
                return 
    Encrypt(obj.ToString(), PhraseSaltAlgorithmIterationsVectorKeySize);
            }
        } 
    du hast jeweils 2 public methoden in der statischen klasse, eine wo du direct einfach nur einen string als parameter eingibst und diesen encryptest/decryptes (dazu schau dir den statischen konstruktor an, diese werte werden benutzt fuer die encryption)
    und wo du alle parameter selber setzten kannst etc.

    die parameter bei dem eifnachen en/decrypt sind object du solltest aber strings benutzen und oder so umschreiben dass das object XML serialisierbar ist etc.
    naja ufjedenfall kann man des noc herweitern etc. viel spass..

  3. #3
    Mitglied

    (Threadstarter)


    Registriert seit
    Jun 2011
    Beiträge
    21

    Wink Re: [C#] Programm zum Ver- und Entschlüsseln von Dateien

    Hallo und erst mal Danke.

    weiss auch nicht wieso du bei den filestreams -15 bzw -16 machst ?!?!
    Also im Verschlüsseln kennzeichnet der die Datei mit :

    Code:
    opf2.FileName + "." + s + ".leocrypt"
    Das wird nun bei der Entschlüsselung wieder rückgängig gemacht.

    Bei der Key - Nummer gibt es ja einstellige Zahlen(0,1,2,3,4,5,6,7,8,9) aber auch ne zweistellige Zahl(10). Das wird wie bereits gesagt dann wieder entfernt.

    aufjedenfall siehts danach aus als ob du irgendwo die laenge des "arrays" nicht auf die laenge des inhalts der datei setzt sodass nur ein teil eingelesen wird etc.
    Was meinst du damit?

    Thx schon mal


    LeoFSU

  4. #4
    Mitglied Avatar von Dr-Strangelove
    Registriert seit
    Nov 2003
    Beiträge
    77

    Standard Re: [C#] Programm zum Ver- und Entschlüsseln von Dateien

    Just FYI:
    DES gilt heuzutage mehr oder weniger als gebrochen. Sollte also prinzipiel nur noch dann verwendet werden wenn es unbedingt erforderlich ist (Bspw, Altlasten, Hardware-Performance).

    In allen anderen Fällen ist AES deutlich sicherer.

    http://msdn.microsoft.com/en-us/libr...eprovider.aspx

  5. #5
    Mitglied

    (Threadstarter)


    Registriert seit
    Jun 2011
    Beiträge
    21

    Standard Re: [C#] Programm zum Ver- und Entschlüsseln von Dateien

    Hat dann dafür vieleicht jemand ne Lösung??

  6. #6
    Mitglied
    Registriert seit
    Aug 2007
    Beiträge
    264

    Standard Re: [C#] Programm zum Ver- und Entschlüsseln von Dateien

    Zitat Zitat von LeoFSU Beitrag anzeigen

    Original - Text:

    ...

    Text, der rauskommt:

    ...

    Weiß vielleicht jemand meinen Fehler??
    Die ersten 8 Bytes sind falsch, das schreit doch nach dem falschen IV beim Entschlüsseln.
    Ohne jetzt diese MS CSP Schnittstelle genau zu kennen, sagt mir aber MSDN, dass bei CreateEn/Decryptor jeweils der "aktuelle IV" genommen wird. Benutzen Deine En/Decrypt Programme aber nicht denselben - k.a. wo der "aktuelle" herkommt, - klappt es natürlich nicht.

    Ansonsten verwirrt mich, das der Blockmode (ECB, CBC ...) eingestellt werden muss/kann. Irgendwie wird anscheinend ECB gemacht, aber beim ersten Block doch ein IV verwendet. Sehr obskur.

    Für Dein Problem solltest Du jedenfalls mal einen IV (nimm einfach den Standard, der nur aus 0x00en besteht) bei en/decrypt übergeben, dann wird es wohl klappen.

    Ansonsten: DES ist seit 10 Jahren obsolet, Du solltest mindestens Triple-DES (gibt es in System.Security ja auch) nehmen. Und Schlüssel per Email verschicken? Oder sind die dann mit PGP o.ä. verschlüsselt. Ansonsten kannst Du Dir das auch sparen.

  7.  
     
     

Berechtigungen

  • Neue Themen erstellen: Nein
  • Themen beantworten: Nein
  • Anhänge hochladen: Nein
  • Beiträge bearbeiten: Nein
  •