Мета роботи – вивчення простих методів шифрування та дешифрування інформації та їх особливостей.
Короткі теоретичні відомості
Криптографічні системи.
Перетворення секретної інформації – це кодування даних, яке використовується для маскування інформації. Ці перетворення змінюють дані, представлені в явній формі, так, що вони стають нерозпізнаваними (з певною мірою надійності) неавторизованими людьми. Шифрування, тобто перетворення секретної інформації, є особливо ефективним засобом проти несанкціонованого доступу до повідомлень, які передаються по лініях зв'язку і неавторизованих доступів до даних, що зберігаються у віддалених файлах. Навіть просте перетворення секретної інформації є ефективним засобом, що дає можливість приховати її значення від більшості користувачів.
У загальній формі в криптографічній системі початкове повідомлення М і ключ К є входами в деякий перетворюючий пристрій (який може бути реалізоване або апаратно, або програмно). Якщо до лінії зв'язку підключиться зловмисник, він зможе викрасти зашифроване повідомлення (або шифровку) Е. Процес відновлення повідомлення при невідомому ключі називаеться дешифруванням.
Початкове повідомлення може бути замасковане за рахунок процедури перетворення. На іншому кінці незахищеної (по допущенню) лінії зв'язку знаходиться апаратний або програмний засіб, який розшифровує повідомлення для отримання початкового тексту.
Шифрування підстановкою
Прямі підстановки.
У прямих підстановках кожний знак початкового тексту замінюється одним або декількома знаками. Одним з важливих підкласів прямих підстановок є моноалфавітні підстановки, в яких встановлюється взаємооднозначна відповідність між кожним знаком аі алфавіту повідомлень А і відповідним знаком hj зашифрованого тексту.
Дуже простим прикладом перетворення секретної інформації є шифр Цезаря, який, за переказами, був використаний ще Юлієм Цезарем . Рядок знаків YGBPCGFBOQTGBUPQYBHQTBDCVVGTBUMKKPI є зашифрованою формою наступного повідомлення: WE NEED VORE SNOW FOR BETTER SKIING (Для кращого катання на лижах треба більше снігу).
Багатоалфавітні підстановки.
Проста багатоалфавітна підстановка послідовно і циклічно міняє алфавіти, що використовуються. При u-алфавітній підстановці знак т1, з початкового повідомлення замінюється знаком з алфавіту В1, т2 відповідним з алфавіту В2. .., ті - знаком з алфавіту Ві, mі+1 знову з алфавіту В1 і т. д.
ВХІДНИЙ ЗНАК: m1,m2,m3,m4,m5,m6,m7
АЛФАВІТ ПІДСТАНОВКИ: B1,B2,B3,B4,B5,B1,B2,.
Ефект використання багатоалфавітної підстановки полягає в тому, що забезпечується маскування природної частотної статистики початкової мови L, оскільки конкретний знак з алфавіту А може бути перетворений в декілька різних знаків шифрувального алфавіту В. Рівень захисту, що забезпечується теоретично, пропорційний довжині періоду в послідовності алфавітів, що використовуються.
Як приклад приведемо використання ключа восьмибуквенного слова SECURSTY, що повторюється для шифрування тексту. Запишемо під кожною початковою буквою відповідну букву ключа. Потім будемо розглядати алфавіт, як кільце, що складається з 27 символів. Привласнюючи відповідно значення 0-пропуск, 1-А, 2=В,...,26=Z, будемо мати восьмиалфавітиий шифр підстановки. Ми можемо розглядати перший алфавіт як такий що зсуває кожний знак, вміщений в кільце, на 19 (S), тобто W стає О, А стає Т, В стає U і т. д.; другий алфавіт, як зсуваючий кожний знак на 5 (Е), тобто Е стає J, А стає F, В стає G і т. д. Використовуючи додавання по модулю 27 отримаємо такий зашифрований текст:
WE NEED MORE SNOW FOR BETTER SKIING
SECURITYSECURITYSECURITYSECURITYSE
OJCHWNXYETUZRAGMOEIVCLYHLRADGASJ
Монофонічні шифри
Монофонічний шифр являє собою багатоалфавітний шифр підстановки, що зрівнює частоту появи зашифрованих знаків і таким чином захищає шифрований текст від розкриття за допомогою частотного аналізу. Для знаків, що зустрічаються часто, потрібна відносно велика кількість зашифрованих еквівалентів. У той же час для знаків, що використовуються нечасто, може виявитися достатнім один або два зашифрованих знаки.
Перестановки
Знаки початкового тексту можна переставляти відповідно до деякого правила. Наприклад, знаки тексту в явній формі WE/NEED/MORE/SNOW/FOR/BETTER/SKIING можуть бути переставлені відповідно до ключа: “переставити угрупування з чотирьох букв, що знаходяться в порядку 1 2 3 4 в порядок 3 1 4 2”. Первинний текст спочатку розбивається на групи WE/N_EED/_ MORE_ /SNO_W/FO_R/BE_TTER_/SKI_ING+, а потім перетворюється в зашифрований текст: /WNE_DE/E_RMEO_N/OS_FWO/_BRE/_ETRT_K/IS_GIXN. Коса межа відповідає пропуску, а + пустому знаку, що використовується для доповнення початкового тексту. Часто з кожним початковим алфавітом використовується декілька пустих знаків (нулів). Однак, якщо зловмисник відгадає довжину угрупування, то він легко може потім зробити різні можливі перестановки, особливо використовуючи ЕОМ.
Частотний аналіз
Більшість штучних мов (і всі природні мови) мають характерний частотний розподіл букв і інших знаків. Наприклад, буква Е найбільш часто зустрічається в англійській мові, а Z найбільш рідка. Однак це зовсім не говорить про те, що не будуть попадатися англійські (вихідні), повідомлення, в яких інша буква буде зустрічатися частіше, ніж Е, і рідше, ніж Z. Але для дуже великого числа англійських повідомлень можуть бути встановлені певні характерні частоти.
Більшість повідомлень, зашифрованих методом перестановки або одноалфавітної підстановки, зберігають характерний частотний розподіл і, таким чином, дають крипто-аналітику шлях до розкриття шифру. Криптоаналітики часто використовують індекс відповідності (ІС) для визначення того, чи знаходяться вони на правильному шляху.
Практична частина
Текст для шифрування
Edgar Allan Poe was born in Boston, Massachusetts, on January 19, 1809. Poe's father and mother, both professional actors, died before the poet was three and John and Frances Allan raised him as a foster child in Richmond, Virginia. John Allan, a prosperous tobacco exporter, sent Poe to the best boarding schools and later to the University of Virginia, where Poe excelled academically. After less than one year of school, however, he was forced to leave the University when Allan refused to pay his gambling debts. Poe returned briefly to Richmond, but his relationship with Allan deteriorated. In 1827, he moved to Boston and enlisted in the United States Army. His first collection of poems, Tamerlane, and Other Poems, was published that year. In 1829, he published a second collection entitled Al Aaraaf, Tamerlane, and Minor Poems. Neither volume received significant critical or public attention. Following his Army service, Poe was admitted to the United States Military Academy, but he was again forced to leave for lack of financial support. He then moved into the home of his aunt, Mrs. Maria Clemm and her daughter Virginia, in Baltimore, Maryland. Poe began to sell short stories to magazines at around this time, and, in 1835, he became the editor of the Southern Literary Messenger in Richmond. He brought his aunt and twelve-year-old cousin, Virginia Clemm, with him to Richmond. He married Virginia in 1836. Over the next ten years, Poe would edit a number of literary journals including the Burton's Gentleman's Magazine and Graham's Magazine in Philadelphia and the Broadway Journal in New York City. It was during these years that he established himself as a poet, a short-story writer, and an editor. He published some of his best-known stories and poems including "The Fall of the House of Usher," "The Tell-Tale Heart," "The Murders in the Rue Morgue," and "The Raven." After Virginia's death from tuberculosis in 1847, Poe's life-long struggle with depression and alcoholism worsened. He returned briefly to Richmond in 1849 and then set out for an editing job in Philadelphia. For unknown reasons, he stopped in Baltimore. On October 3, 1849, he was found in a state of semi-consciousness. Poe died four days later of "acute congestion of the brain."Poe's work as an editor, a poet, and a critic had a profound impact on American and international literature. His stories mark him as one of the originators of both horror and detective fiction. Many anthologies credit him as the "architect" of the modern short story. He was also one of the first critics to focus primarily on the effect of the style and of the structure in a literary work; as such, he has been seen as a forerunner to the "art for art's sake" movement. French Symbolists such as Mallarme and Rimbaud claimed him as a literary precursor. Baudelaire spent nearly fourteen years translating Poe into French. Today, Poe is remembered as one of the first American writers to become a major figure in world literature.
Ключ для шифрування
! #"%$'&)(+*-,/.1032547698;:=<?>A@CBEDGFIHKJMLONQPSRUTWVYX[Z]\_^a`cbedgfihkjmlonqpsrutwvyx{z}|~ЃЂѓ‚…„‡†‰€‹ЉЌЊЏЋ‘ђ“’•”—–™›љќњџћЎ ЈўҐ¤§¦©Ё«Є¬Ї®±°іІµґ·¶№ё»єЅјїѕБАГВЕДЗЖЙИЛКНМПОСРУТХФЧЦЩШЫЪЭЬЯЮбагведзжйилкнмпосрутхфчцщшыъэьяю
Текст програми для шифрування і розшифрування
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<fstream.h>
void main(void)
{
char array_alfavit_n[257],filename[64],array_alfavit_o[257],ch,symbol;
unsigned int i,j;
FILE *fill,*fill_1;
clrscr();
cout<<"Enter file name:> ";
cin>>filename;
for(i=0;i<=256;i++) //Obnylutu masuvu
array_alfavit_n[i]=0;
for(i=0;i<256;i++) //Stvoryjemo alfavit
array_alfavit_n[i]=i;
//Stvoryjemo kljych
for(i=0;i<255;i++)
{
symbol=array_alfavit_n[i];
array_alfavit_o[i+1]=symbol;
symbol=array_alfavit_n[i+1];
array_alfavit_o[i]=symbol;
i++;
}
fill_1=fopen("key.txt","w");
for(i=0;i<256;i++)
fprintf(fill_1,"%c",array_alfavit_o[i]);
fill_1=fopen(filename,"r");
fill=fopen("shufr.txt","w");
while(!feof(fill_1)) //Shufryvannja
{
symbol=fgetc(fill_1);
if(symbol!=-1)
fputc(array_alfavit_o[symbol],fill);
}
fclose(fill);
fclose(fill_1);
//2
fill_1=fopen("shufr.txt","r");
fill=fopen("deshufr.txt","w");
cout<<"Rozshufryvatu?(y/n) ";
cin>>symbol;
if(symbol=='y')
{
while(!feof(fill_1)) //Deshufryvannja
{
symbol=fgetc(fill_1);
if(symbol!=-1)
fputc(array_alfavit_o[symbol],fill);
}
}
fclose(fill);
fclose(fill_1);
}
Текст зашифрованого файлу
Def`s!@mm`o!Qnd!v`r!cnso!ho!Cnruno-!L`rr`bitrduur-!no!K`ot`sx!08-!0918/!Qnd&r!g`uids!`oe!lnuids-!cnui!qsngdrrhno`m!`bunsr-!ehde!cdgnsd!uid!qndu!v`r!uisdd!`oe!Knio!`oe!Gs`obdr!@mm`o!s`hrde!ihl!`r!`!gnruds!bihme!ho!Shbilnoe-!Whsfhoh`/!Knio!@mm`o-!`!qsnrqdsntr!unc`bbn!dyqnsuds-!rdou!Qnd!un!uid!cdru!cn`sehof!rbinnmr!`oe!m`uds!un!uid!Tohwdsrhux!ng!Whsfhoh`-!vidsd!Qnd!dybdmmde!`b`edlhb`mmx/!@guds!mdrr!ui`o!nod!xd`s!ng!rbinnm-!invdwds-!id!v`r!gnsbde!un!md`wd!uid!Tohwdsrhux!vido!@mm`o!sdgtrde!un!q`x!ihr!f`lcmhof!edcur/Qnd!sdutsode!cshdgmx!un!Shbilnoe-!ctu!ihr!sdm`uhnorihq!vhui!@mm`o!edudshns`ude/!Ho!0936-!id!lnwde!un!Cnruno!`oe!domhrude!ho!uid!Tohude!Ru`udr!@slx/!Ihr!ghsru!bnmmdbuhno!ng!qndlr-!U`ldsm`od-!`oe!Nuids!Qndlr-!v`r!qtcmhride!ui`u!xd`s/!Ho!0938-!id!qtcmhride!`!rdbnoe!bnmmdbuhno!douhumde!@m!@`s``g-!U`ldsm`od-!`oe!Lhons!Qndlr/!Odhuids!wnmtld!sdbdhwde!rhfohghb`ou!bshuhb`m!ns!qtcmhb!`uudouhno/!Gnmmnvhof!ihr!@slx!rdswhbd-!Qnd!v`r!`elhuude!un!uid!Tohude!Ru`udr!Lhmhu`sx!@b`edlx-!ctu!id!v`r!`f`ho!gnsbde!un!md`wd!gns!m`bj!ng!gho`obh`m!rtqqnsu/!Id!uido!lnwde!houn!uid!inld!ng!ihr!`tou-!Lsr/!L`sh`!Bmdll!`oe!ids!e`tfiuds!Whsfhoh`-!ho!C`muhlnsd-!L`sxm`oe/Qnd!cdf`o!un!rdmm!rinsu!runshdr!un!l`f`{hodr!`u!`sntoe!uihr!uhld-!`oe-!ho!0924-!id!cdb`ld!uid!dehuns!ng!uid!Rntuidso!Mhuds`sx!Ldrrdofds!ho!Shbilnoe/!Id!csntfiu!ihr!`tou!`oe!uvdmwd,xd`s,nme!bntrho-!Whsfhoh`!Bmdll-!vhui!ihl!un!Shbilnoe/!Id!l`sshde!Whsfhoh`!ho!0927/!Nwds!uid!odyu!udo!xd`sr-!Qnd!vntme!dehu!`!otlcds!ng!mhuds`sx!kntso`mr!hobmtehof!uid!Ctsuno&r!Fdoumdl`o&r!L`f`{hod!`oe!Fs`i`l&r!L`f`{hod!ho!Qihm`edmqih`!`oe!uid!Csn`ev`x!Kntso`m!ho!Odv!Xnsj!Bhux/!Hu!v`r!etshof!uidrd!xd`sr!ui`u!id!dru`cmhride!ihlrdmg!`r!`!qndu-!`!rinsu,runsx!vshuds-!`oe!`o!dehuns/!Id!qtcmhride!rnld!ng!ihr!cdru,jonvo!runshdr!`oe!qndlr!hobmtehof!#Uid!G`mm!ng!uid!Intrd!ng!Trids-#!#Uid!Udmm,U`md!Id`su-#!#Uid!Ltsedsr!ho!uid!Std!Lnsftd-#!`oe!#Uid!S`wdo/#!@guds!Whsfhoh`&r!ed`ui!gsnl!utcdsbtmnrhr!ho!0956-!Qnd&r!mhgd,mnof!rustffmd!vhui!edqsdrrhno!`oe!`mbninmhrl!vnsrdode/!Id!sdutsode!cshdgmx!un!Shbilnoe!ho!0958!`oe!uido!rdu!ntu!gns!`o!dehuhof!knc!ho!Qihm`edmqih`/!Gns!tojonvo!sd`rnor-!id!runqqde!ho!C`muhlnsd/!No!Nbuncds!2-!0958-!id!v`r!gntoe!ho!`!ru`ud!ng!rdlh,bnorbhntrodrr/!Qnd!ehde!gnts!e`xr!m`uds!ng!#`btud!bnofdruhno!ng!uid!cs`ho/#Qnd&r!vnsj!`r!`o!dehuns-!`!qndu-!`oe!`!bshuhb!i`e!`!qsngntoe!hlq`bu!no!@ldshb`o!`oe!houdso`uhno`m!mhuds`utsd/!Ihr!runshdr!l`sj!ihl!`r!nod!ng!uid!nshfho`unsr!ng!cnui!inssns!`oe!edudbuhwd!ghbuhno/!L`ox!`ouinmnfhdr!bsdehu!ihl!`r!uid!#`sbihudbu#!ng!uid!lnedso!rinsu!runsx/!Id!v`r!`mrn!nod!ng!uid!ghsru!bshuhbr!un!gnbtr!qshl`shmx!no!uid!dggdbu!ng!uid!ruxmd!`oe!ng!uid!rustbutsd!ho!`!mhuds`sx!vnsj:!`r!rtbi-!id!i`r!cddo!rddo!`r!`!gnsdstoods!un!uid!#`su!gns!`su&r!r`jd#!lnwdldou/!Gsdobi!Rxlcnmhrur!rtbi!`r!L`mm`sld!`oe!Shlc`te!bm`hlde!ihl!`r!`!mhuds`sx!qsdbtsrns/!C`tedm`hsd!rqdou!od`smx!gntsuddo!xd`sr!us`orm`uhof!Qnd!houn!Gsdobi/!Une`x-!Qnd!hr!sdldlcdsde!`r!nod!ng!uid!ghsru!@ldshb`o!vshudsr!un!cdbnld!`!l`kns!ghftsd!ho!vnsme!mhuds`utsd/
Текст програми для дешифрації методом частотного аналізу
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<iostream.h>
#include<fstream.h>
class sym
{
public:
char ch;
float chastota;
};
void main(void)
{
sym alfavit[257],key[257];
char symbol,filename[64];
float tsufra;
int i,j,n,m=0;
long int siz,siz1;
FILE *fill_et,*fill_sh;
clrscr();
for(i=0;i<257;i++)
{
alfavit[i].ch=0;
alfavit[i].chastota=0;
key[i].ch=0;
key[i].chastota=0;
}
siz=0;
cout<<"Enter file name > ";
cin>>filename;
fill_et=fopen(filename,"r");
while(!feof(fill_et)) //Formyjemo 1tab
{
siz++;
symbol=fgetc(fill_et);
if(symbol!=-1)
{
alfavit[symbol].ch=symbol;
alfavit[symbol].chastota++;
}
}
for(j=0;j<255;j++) //Sortyvannja
for(i=0;i<255;i++)
if(alfavit[i+1].chastota>alfavit[i].chastota)
{
tsufra=alfavit[i+1].chastota;
alfavit[i+1].chastota=alfavit[i].chastota;
alfavit[i].chastota=tsufra;
symbol=alfavit[i+1].ch;
alfavit[i+1].ch=alfavit[i].ch;
alfavit[i].ch=symbol;
}
cout<<"\n"<<"Tab_1"<<"\n\n";
for(i=0;i<256;i++)
{
if(alfavit[i].chastota==0) break;
cout<<alfavit[i].ch<<"="<<alfavit[i].chastota<<" ";
}
n=i;
siz1=0;
fclose(fill_et);
fill_et=fopen("shufr.txt","r");
while(!feof(fill_et)) //Formyjemo 2tab
{
siz1++;
symbol=fgetc(fill_et);
if(symbol!=-1)
{
key[symbol].ch=symbol;
key[symbol].chastota++;
}
}
for(j=0;j<255;j++) //Sortyvannja
for(i=0;i<255;i++)
if(key[i+1].chastota>key[i].chastota)
{
tsufra=key[i+1].chastota;
key[i+1].chastota=key[i].chastota;
key[i].chastota=tsufra;
symbol=key[i+1].ch;
key[i+1].ch=key[i].ch;
key[i].ch=symbol;
}
cout<<"\n\n"<<"Tab_2"<<"\n\n";
for(i=0;i<256;i++)
{
if(key[i].chastota==0) break;
cout<<key[i].ch<<"="<<key[i].chastota<<" ";
}
m=i;
fclose(fill_et);
fill_et=fopen("deshufr_2.txt","w");
fill_sh=fopen("shufr.txt","r");
while(!feof(fill_sh))
{
symbol=fgetc(fill_sh);
if(symbol!=-1)
for(i=0;i<m;i++)
if(symbol==key[i].ch)
fprintf(fill_et,"%c",alfavit[i].ch);
}
fclose(fill_et);
fclose(fill_sh);
}
Таблиці зустрічання символів в тексті і зашифрованому тексті
Enter file name > 1.txt
Текст дешифрованого файлу
Edgar Allan Poe was born in Boston, Massachusetts, on January 19, 1809. Poe's father and mother, both professional actors, died before the poet was three and John and Frances Allan raised him as a foster child in Richmond, Virginia. John Allan, a prosperous tobacco exporter, sent Poe to the best boarding schools and later to the University of Virginia, where Poe excelled academically. After less than one year of school, however, he was forced to leave the University when Allan refused to pay his gambling debts.
Poe returned briefly to Richmond, but his relationship with Allan deteriorated. In 1827, he moved to Boston and enlisted in the United States Army. His first collection of poems, Tamerlane, and Other Poems, was published that year. In 1829, he published a second collection entitled Al Aaraaf, Tamerlane, and Minor Poems. Neither volume received significant critical or public attention. Following his Army service, Poe was admitted to the United States Military Academy, but he was again forced to leave for lack of financial support. He then moved into the home of his aunt, Mrs. Maria Clemm and her daughter Virginia, in Baltimore, Maryland.
Poe began to sell short stories to magazines at around this time, and, in 1835, he became the editor of the Southern Literary Messenger in Richmond. He brought his aunt and twelve-year-old cousin, Virginia Clemm, with him to Richmond. He married Virginia in 1836. Over the next ten years, Poe would edit a number of literary journals including the Burton's Gentleman's Magazine and Graham's Magazine in Philadelphia and the Broadway Journal in New York City. It was during these years that he established himself as a poet, a short-story writer, and an editor. He published some of his best-known stories and poems including "The Fall of the House of Usher," "The Tell-Tale Heart," "The Murders in the Rue Morgue," and "The Raven." After Virginia's death from tuberculosis in 1847, Poe's life-long struggle with depression and alcoholism worsened. He returned briefly to Richmond in 1849 and then set out for an editing job in Philadelphia. For unknown reasons, he stopped in Baltimore. On October 3, 1849, he was found in a state of semi-consciousness. Poe died four days later of "acute congestion of the brain."
Poe's work as an editor, a poet, and a critic had a profound impact on American and international literature. His stories mark him as one of the originators of both horror and detective fiction. Many anthologies credit him as the "architect" of the modern short story. He was also one of the first critics to focus primarily on the effect of the style and of the structure in a literary work; as such, he has been seen as a forerunner to the "art for art's sake" movement. French Symbolists such as Mallarme and Rimbaud claimed him as a literary precursor. Baudelaire spent nearly fourteen years translating Poe into French. Today, Poe is remembered as one of the first American writers to become a major figure in world literature.
Висновок: На цій лабораторній роботі я вивчив прості методи шифрування та дешифрування інформації та їх особливості.
Міністерство освіти та науки України
Національний університет „Львівська політехніка”
Звіт
до лабораторної роботи №6
на тему:
„Методи шифрування та дешифрування інформації та їх особливості”
[ім’я автора приховано]
Превірив:
Грицишин Я.
-Львів 2009-