Question

J'essaie de stocker un mot de passe dans un fichier que je voudrais récupérer pour plus tard. Le hachage n'est pas une option car j'ai besoin du mot de passe pour me connecter ultérieurement à un serveur distant.

Le code suivant fonctionne bien, mais il crée une sortie différente à chaque fois, même si la clé est la même. C'est mauvais car lorsque l'application s'arrête et redémarre, je ne pourrai plus récupérer mon mot de passe. Comment puis-je stocker les mots de passe dans un fichier et les récupérer plus tard?

public class EncyptDecrypt {

    static System.Security.Cryptography.TripleDESCryptoServiceProvider keyProv = new System.Security.Cryptography.TripleDESCryptoServiceProvider();

    public static System.Security.Cryptography.TripleDESCryptoServiceProvider KeyProvider {
        get {
            keyProv.Key = new byte[] { /* redacted with prejudice */ };
            return keyProv;
        }
    }

    public static string Encrypt(string text, SymmetricAlgorithm key) {

        if (text.Equals(string.Empty)) return text;

        // Create a memory stream.
        MemoryStream ms = new MemoryStream();

        // Create a CryptoStream using the memory stream and the
        // CSP DES key.
        CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);

        // Create a StreamWriter to write a string
        // to the stream.
        StreamWriter sw = new StreamWriter(encStream);

        // Write the plaintext to the stream.
        sw.WriteLine(text);

        // Close the StreamWriter and CryptoStream.
        sw.Close();
        encStream.Close();

        // Get an array of bytes that represents
        // the memory stream.
        byte[] buffer = ms.ToArray();

        // Close the memory stream.
        ms.Close();

        // Return the encrypted byte array.
        return System.Convert.ToBase64String(buffer);
    }

    // Decrypt the byte array.
    public static string Decrypt(string cypherText, SymmetricAlgorithm key) {

        if (cypherText.Equals(string.Empty)) return cypherText;

        string val;

        try {
            // Create a memory stream to the passed buffer.
            MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(cypherText));

            // Create a CryptoStream using the memory stream and the
            // CSP DES key.
            CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);

            // Create a StreamReader for reading the stream.
            StreamReader sr = new StreamReader(encStream);

            // Read the stream as a string.
            val = sr.ReadLine();

            // Close the streams.
            sr.Close();
            encStream.Close();
            ms.Close();
        }
        catch (System.Exception) {

            return string.Empty;
        }

        return val;
    }
}
Était-ce utile?

La solution

Je pense que ce qui se passe, c'est que le fournisseur de cryptographie génère de manière aléatoire un IV. Spécifiez ceci et cela ne devrait plus différer.

Modifier: vous pouvez le faire dans votre fournisseur de clé en définissant la propriété IV.

Autres conseils

Selon la documentation de CreateEncryptor:

  

Si la propriété IV actuelle est nulle   référence (rien dans Visual Basic),   la méthode GenerateIV est appelée   créer un nouveau IV aléatoire.

Cela rendra le texte chiffré différent à chaque fois.

Remarque: une solution à ce problème est décrite ici où je vous suggère d’ajouter le texte en clair avec un mac ... alors le premier bloc de texte chiffré est effectivement le vecteur IV, mais il est tout à fait reproductible

Vous devez spécifier un vecteur d’initialisation (IV) même si vous en générez un de manière aléatoire. Si vous utilisez une IV aléatoire, vous devez la stocker avec le texte crypté pour pouvoir l'utiliser plus tard lors du déchiffrement. Vous pouvez également dériver une IV de certaines autres données (par exemple, si vous cryptez un mot de passe, vous pouvez dériver l'IV de le nom d'utilisateur).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top