Использование шифрования AES в C #

Кстати ... Как обновлять его каждый раз, чтобы он печатал mi в одном месте, просто изменяйте число.

blockquote>

В общем, способ сделайте это с помощью управляющих кодов терминала . Это особенно простой случай, для которого вам нужен только один специальный символ: U + 000D CARRIAGE RETURN, который написан '\r' в Python (и многих других языках). Вот полный пример, основанный на вашем коде:

from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\n") # move the cursor to the next line

Некоторые вещи об этом могут быть удивительными:

  • \r идет в начале строки, поэтому что, пока программа запущена, курсор всегда будет после номера. Это не просто косметика: некоторые терминальные эмуляторы очень запутаны, если вы делаете это наоборот.
  • Если вы не включили последнюю строку, то после завершения программы ваша оболочка напечатает подсказка сверху номера.
  • В некоторых системах требуется stdout.flush, или вы не получите какой-либо вывод. Другие системы могут не требовать этого, но это не наносит вреда.

Если вы обнаружите, что это не сработает, первое, что вы должны подозревать, это то, что ваш эмулятор терминала неисправен , Программа vttest может помочь вам протестировать ее.

Вы можете заменить stdout.write на инструкцию print, но я предпочитаю не смешивать print с прямым использованием файла объекты.

118
задан Dan Esparza 22 March 2017 в 17:25
поделиться

3 ответа

Используя AES или реализацию AES? Для использования AES существует Система. Безопасность. Криптография. Класс RijndaelManaged.

9
ответ дан DCNYAM 22 March 2017 в 17:25
поделиться
  • 1
    Спасибо за ссылку. Но it' s не очень правильно написанный:), Когда автор говорит "It seems to tax the processor a bit more, though" немного неопределенные звуки.. doesn' t это? – rinchik 3 March 2013 в 10:59

Если Вы просто хотите использовать встроенного crypto поставщика RijndaelManaged, проверить следующую статью справки (это также имеет простой пример кода):

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx

И на всякий случай Вам нужен образец второпях, здесь это находится во всей своей незаконно заимствуемой славе:

using System;
using System.IO;
using System.Security.Cryptography;

namespace RijndaelManaged_Example
{
    class RijndaelExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the RijndaelManaged 
                // class.  This generates a new key and initialization  
                // vector (IV). 
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {

                    myRijndael.GenerateKey();
                    myRijndael.GenerateIV();
                    // Encrypt the string to an array of bytes. 
                    byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

                    // Decrypt the bytes to a string. 
                    string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

                    //Display the original data and the decrypted data.
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("Round Trip: {0}", roundtrip);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
        static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption. 
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }


            // Return the encrypted bytes from the memory stream. 
            return encrypted;

        }

        static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold 
            // the decrypted text. 
            string plaintext = null;

            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption. 
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream 
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;

        }
    }
}
143
ответ дан Kcvin 22 March 2017 в 17:25
поделиться

Для более полного примера, который выполняет вывод ключей в дополнение к шифрованию AES, см. Ответ и ссылки, размещенные в Получение шифрования AES для работы через Javascript и C # .

ИЗМЕНИТЬ
примечание: Криптография Javascript считается вредоносной. Стоит прочитать.

8
ответ дан 24 November 2019 в 01:57
поделиться
Другие вопросы по тегам:

Похожие вопросы: