public static void WriteKey(RSAKey key, string fileName)
 {
     using (StreamWriter streamWriter = new StreamWriter(fileName))
     {
         streamWriter.Write("{0} {1}", key.data, key.N);
     }
 }
        public static RSAKey ReadKey(string fileName)
        {
            RSAKey key = new RSAKey();
            FileStream fileStream = new FileStream(fileName, FileMode.Open);

            string fileContents;
            using (StreamReader reader = new StreamReader(fileStream))
            {
                fileContents = reader.ReadToEnd();
            }
            fileStream.Close();

            Int64[] dataArray = fileContents.Split().Select(x => Int64.Parse(x)).ToArray();
            if (dataArray.Length != 2)
            {
                throw new Exception("Error reading key from file!");
            }
            key.data = dataArray[0];
            key.N = dataArray[1];
            return key;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Генерирует ключи для шифрования и расшифрования
        /// </summary>
        public void GenerateKeys()
        {
            random = new Random((int)DateTime.Now.Ticks % Int32.MaxValue);
            simpleList = GenerateSimpleNumbersList(1000);

            Int64 P = GenerateRandomNumberInt16();
            Int64 Q = P;
            while (P == Q)
            {
                Q = GenerateRandomNumberInt16();
            }
            Int64 N = P * Q;
            Int64 M = (P - 1) * (Q - 1);
            Int64 E = 0;
            do
            {
                E = GenerateRandomNumberInt32();
            }
            while (EuclidsAlgorithm(E, M) != 1);
            Int64 D = ExtendedEuclid(E, M);

            RSAKey publicKey = new RSAKey();
            publicKey.data = E;
            publicKey.N = N;

            RSAKey privateKey = new RSAKey();
            privateKey.data = D;
            privateKey.N = N;

            KeyFileWriter.WriteKey(publicKey, PUBLIC_KEY_FILE_NAME);
            KeyFileWriter.WriteKey(privateKey, PRIVATE_KEY_FILE_NAME);
        }