Вход

Пример высокоуровневого протокола безопасного исполнения SQL-запросов к СУБД

Рекомендуемая категория для самостоятельной подготовки:
Курсовая работа*
Код 73408
Дата создания 2014
Страниц 22
Мы сможем обработать ваш заказ (!) 29 марта в 18:00 [мск]
Файлы будут доступны для скачивания только после обработки заказа.
2 030руб.
КУПИТЬ

Содержание

ОГЛАВЛЕНИЕ
1. Краткая справка об использованном алгоритме шифрования и процедуре обмене ключей шифрования 3
2. Создание приложения – сервера. 4
3. Создание приложения – клиента. 5
4. Настройка и применение по назначению. 6
Приложения. 8

Фрагмент работы для ознакомления

csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Security.Cryptography;using System.IO;namespace SecureSQLClient{publicclassNVEncoder {List<byte> data;public NVEncoder() { data = newList<byte>(); }publicvoid Add(string name, byte[] data) {if (string.IsNullOrEmpty(name)) return;if (data == null || data.Length == 0) return;byte[] nameData = Encoding.UTF8.GetBytes(name);byte[] nameLength = BitConverter.GetBytes(nameData.Length);this.data.AddRange(nameLength);this.data.AddRange(nameData);byte[] dataLenght = BitConverter.GetBytes(data.Length);this.data.AddRange(dataLenght);this.data.AddRange(data); }publicbyte[] ToPackage() {return data.ToArray(); } }publicclassNVDecoder {privatebyte[] data;privateint pos;public NVDecoder(byte[] data) {this.data = data;this.pos = 0; }publicbyte[] ReadData(string name) {if (data == null) returnnull;int pos_save = pos;int cycle = 0;while (cycle == 0 || pos < pos_save) {if ((pos + 4) >= data.Length) { pos = 0;returnnull; }int len = BitConverter.ToInt32(data, pos); pos += 4;if ((pos + len) >= data.Length) { pos = 0;returnnull; }string item_name = Encoding.UTF8.GetString(data, pos, len);bool cmpresult = name == item_name; pos += len;if ((pos + 4) >= data.Length) { pos = 0;returnnull; } len = BitConverter.ToInt32(data, pos); pos += 4;if ((pos + len) > data.Length) { pos = 0;returnnull; }if (cmpresult) pos_save = pos; pos += len;if (pos >= data.Length) { cycle = 1; pos = 0; }if (cmpresult) {byte[] result = newbyte[len];Array.Copy(data, pos_save, result, 0, len);return result; } }returnnull; } }publicstructSymParams {publicbyte[] key;publicbyte[] iv; }publicstaticclassRSANVExport {publicstaticbyte[] ExportPublicKey(RSAParameters rsa) {NVEncoder encoder = newNVEncoder(); encoder.Add("e", rsa.Exponent); encoder.Add("m", rsa.Modulus);return encoder.ToPackage(); }publicstaticstring ExportPublicKeyBase64(RSAParameters rsa) {returnConvert.ToBase64String(ExportPublicKey(rsa)); }publicstaticbyte[] ExportAllKey(RSAParameters rsa) {NVEncoder encoder = newNVEncoder(); encoder.Add("d", rsa.D); encoder.Add("dp", rsa.DP); encoder.Add("dq", rsa.DQ); encoder.Add("e", rsa.Exponent); encoder.Add("iq", rsa.InverseQ); encoder.Add("m", rsa.Modulus); encoder.Add("p", rsa.P); encoder.Add("q", rsa.Q);return encoder.ToPackage(); }publicstaticstring ExportAllKeyBase64(RSAParameters rsa) {returnConvert.ToBase64String(ExportAllKey(rsa)); } }publicstaticclassRSANVImport {publicstaticRSAParameters ImportPublicKey(byte[] data) {RSAParameters res = newRSAParameters();NVDecoder decoder = newNVDecoder(data); res.Exponent = decoder.ReadData("e"); res.Modulus = decoder.ReadData("m");return res; }publicstaticRSAParameters ImportPublicKeyBase64(string data) {return ImportPublicKey(Convert.FromBase64String(data)); }publicstaticRSAParameters ImportAllKey(byte[] data) {RSAParameters res = newRSAParameters();NVDecoder decoder = newNVDecoder(data); res.D = decoder.ReadData("d"); res.DP = decoder.ReadData("dp"); res.DQ = decoder.ReadData("dq"); res.Exponent = decoder.ReadData("e"); res.Modulus = decoder.ReadData("m"); res.InverseQ = decoder.ReadData("iq"); res.P = decoder.ReadData("p"); res.Q = decoder.ReadData("q");return res; }publicstaticRSAParameters ImportAllKeyBase64(string data) {return ImportAllKey(Convert.FromBase64String(data)); } }publicclassRSAWrapper {publicstaticRSAParameters GenerateKeyPair(int length) {using (var rsa = newRSACryptoServiceProvider(length)) {return rsa.ExportParameters(true); } }publicstaticbyte[] EncryptAssym(byte[] message, RSAParameters rsa) {using (var provider = newRSACryptoServiceProvider()) { provider.ImportParameters(rsa);return provider.Encrypt(message, true); } }publicstaticbyte[] DecryptAssym(byte[] message, RSAParameters rsa) {using (var provider = newRSACryptoServiceProvider()) { provider.ImportParameters(rsa);return provider.Decrypt(message, true); } }publicstaticSymParams GenerateSymParams() {SymParams result = newSymParams();using (RijndaelManaged myRijndael = newRijndaelManaged()) { myRijndael.GenerateKey(); myRijndael.GenerateIV(); result.key = myRijndael.Key.ToArray(); result.iv = myRijndael.IV.ToArray(); }return result; }publicstaticbyte[] EncryptSym(byte[] data, SymParams symParams) {byte[] encrypted = null;using (RijndaelManaged rijAlg = newRijndaelManaged()) { rijAlg.Key = symParams.key.ToArray(); rijAlg.IV = symParams.iv.ToArray();ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);using (MemoryStream msEncrypt = newMemoryStream()) {using (CryptoStream csEncrypt = newCryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(data, 0, data.Length); csEncrypt.Close(); } encrypted = msEncrypt.ToArray();} }return encrypted; }publicstaticbyte[] DecryptSym(byte[] cipherText, SymParams sp) {byte[] result = null;using (RijndaelManaged rijAlg = newRijndaelManaged()) { rijAlg.Key = sp.key; rijAlg.IV = sp.iv;ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);using (MemoryStream msDecrypt = newMemoryStream()) {using (CryptoStream csDecrypt = newCryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write)) { csDecrypt.Write(cipherText, 0, cipherText.Length); csDecrypt.Close(); } result = msDecrypt.ToArray();} }return result; } }}Keys.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;namespace SecureSQLClient{publicstaticclassKeys {publicstaticstring publicKey = @"AQAAAGUDAAAAAQABAQAAAG2AAAAAz4KSl7GvS/x67Q5p1PmpxReiNQ7viaJipWrcRjlkektPnVrfaeBmdRn9oHSJ7EekIw/9/UJ4QoRjIh+mNw7dSqWuI0awv88D22sd1XYhzjrsPa7DBcjuRd1tGJcH5cM0mF1w16YuFab+GGspwY8ipGd0t1+9/SigH+vJK+fJHOs=";}}Program.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Reflection;namespace SecureSQLClient{classProgram {staticvoid Main(string[] args) {string fileSend = Assembly.GetExecutingAssembly().Location + ".send.dat";string fileRecv = Assembly.GetExecutingAssembly().Location + ".recv.dat";string fileRecvTxt = Assembly.GetExecutingAssembly().Location + ".recv.txt";ContractClient proxy = newContractClient();try {var publicKey = RSANVImport.ImportPublicKeyBase64(Keys.publicKey);var privateKey = RSAWrapper.GenerateKeyPair(1024);var publicKeyForServer = RSANVExport.ExportPublicKeyBase64(privateKey);var firstPartSymKey = RSAWrapper.GenerateSymParams();// отправка половины ключа и получение полного ключа в режиме асинхронного шифрованияvar c = proxy.ChannelFactory.CreateChannel();List<byte> send = newList<byte>(); send.AddRange(RSAWrapper.EncryptAssym(firstPartSymKey.key, publicKey)); send.AddRange(UTF8Encoding.UTF8.GetBytes(publicKeyForServer));var p = c.GetSyncKey(send.ToArray());byte[] pd = RSAWrapper.DecryptAssym(p, privateKey);// формирование ключа для шифрования запросовSymParams sp = newSymParams();sp.iv = newbyte[16]; sp.key = newbyte[32];Array.Copy(pd, 0, sp.iv, 0, 16);Array.Copy(pd, 16, sp.key, 0, 32);while (true) {Console.WriteLine("Enter SQL Query or 'QUIT' for exit: ");string query = Console.ReadLine(); //"SELECT * FROM Employees";if (query == "QUIT" || query == "quit") break;byte[] qsend = RSAWrapper.EncryptSym(UTF8Encoding.UTF8.GetBytes(query), sp);File.WriteAllBytes(fileSend, qsend);Console.WriteLine("SQL Query encrypted in file send.dat. Change file or continue...");Console.ReadLine(); qsend = File.ReadAllBytes(fileSend);byte[] qrecv = c.SQLQuery(qsend);File.WriteAllBytes(fileRecv, qrecv);Console.WriteLine("SQL Query answer received in file recv.dat. Change file or continue...");Console.ReadLine(); qrecv = File.ReadAllBytes(fileRecv);byte[] dec = RSAWrapper.DecryptSym(qrecv, sp);string answer = UTF8Encoding.UTF8.GetString(dec);File.WriteAllText(fileRecvTxt, answer);Console.WriteLine(answer);Console.WriteLine(); } }catch (Exception e) {Console.WriteLine(e.Message); }Console.WriteLine("Длязавершениянажмите <ENTER>.\n\n");Console.ReadLine(); proxy.Close(); } }}

Список литературы

нет
Очень похожие работы
Пожалуйста, внимательно изучайте содержание и фрагменты работы. Деньги за приобретённые готовые работы по причине несоответствия данной работы вашим требованиям или её уникальности не возвращаются.
* Категория работы носит оценочный характер в соответствии с качественными и количественными параметрами предоставляемого материала. Данный материал ни целиком, ни любая из его частей не является готовым научным трудом, выпускной квалификационной работой, научным докладом или иной работой, предусмотренной государственной системой научной аттестации или необходимой для прохождения промежуточной или итоговой аттестации. Данный материал представляет собой субъективный результат обработки, структурирования и форматирования собранной его автором информации и предназначен, прежде всего, для использования в качестве источника для самостоятельной подготовки работы указанной тематики.
bmt: 0.00443
© Рефератбанк, 2002 - 2024