Switch to full style
For C/C++ coders discussions and solutions
Post a reply

ascii codes using of it in c

Mon Jan 12, 2009 2:00 pm

here you can see an example of some programmes with ascii codes..
there is ceasar encryption...
there is affine encryption and decryption..
and there is gcd ))
well this are most kindly examples..
for people who are interestead to see some usage of ascii

well for the affine encryption and decryption i will leave it to you to find why there is a small problem with the codes and they loose the 100% encryption and decryption..it would be interesting to see your thoughts about it ..))

ceasar
cpp code
#include <stdio.h>
#include <string.h>

void menu(void){
printf("Please enter a number: \n"
"1-Encrypt\n"
"2-Decrypt\n"
"3-Exit\n"
"prompt > ");
fflush( stdout );
}

int getchoice(void){
char buff[BUFSIZ];
int choice = 0;
do {
menu();
if(fgets( buff, sizeof buff, stdin ) != NULL){
/* success reading a line, does it make sense? */
if(sscanf( buff, "%d", &choice) != 1){
printf("Enter a number\n");
}
}else{
/* user EOF, just exit now */
choice = 3;
}
}while(choice < 1 || choice > 3);
return choice;
}

void encode(void){
char buff[BUFSIZ];
int i = 0;
int shift_value;
printf( "Doing encrypt\n" );
printf("\nPlease enter the text you wish to encrypt CAPS LOCK ONLY: ");
fgets(buff, sizeof(buff), stdin);
printf("\nEnter your encryption shift value (anything from +1 to 25): ");
scanf("%i", &shift_value);
while(buff != '\0'){
if(buff[i] >= 'A' && buff[i] <= 'Z'){
buff[i] = 'A' + (buff[i] - 'A' + shift_value) % 26;
}
i++;
}
printf("\n Your encrypted text is: %s \n", buff);
}

void decode(void){
char buff[BUFSIZ];
int i = 0;
int shift_value;
printf( "Doing decrypt\n" );
printf("\nPlease enter the text you wish to decrypt CAPS LOCK ONLY: ");
fgets(buff, sizeof(buff), stdin);
printf("\nEnter your encryption shift value (anything from +1 to 25): ");
scanf ("%i", &shift_value);

while(buff[i] != '\0'){
if(buff[i] >= 'A' && buff[i] <= 'Z'){
int c = buff[i] - 'A' - shift_value;
if(c < 0)
c += 26;
buff[i] = 'A' + c % 26;
}
i++;
}
printf("\nYour decrypted text is: %s \n", buff);
}

int main(){
int choice;
while((choice=getchoice()) != 3 ){
if(choice == 1){
encode();
}else{
if(choice == 2){
decode();
}
}
}
return 0;
}



[i]affine encryption

cpp code
#include<stdio.h>
#include<string.h>
void main()
{
int ch,a1,b1,a,b,c,d,d1[15],h,n,i=0;
char str1[80],ek[80];
printf("Dwse to keimeno\n");
gets(str1);
do
{
printf("Dwse to kleidi\na:");
scanf("%d",&a);
printf("\nb:");
scanf("%d",&b);
a1=a;
b1=b;
b=26;
d=1;
while(d!=0)
{


c=a/b;

d=a%b;
d1=d;
a=b;
b=d;
i=i++;



}

n=i-1;





if(d1[n-1]==1)
{
printf("\nOi ariumoi einai prvtoi metaji tous\n\n");
ch=1;

}
else
{
printf("\nOi ariumoi den einai prvtoi metaji tous\n\n");
ch=0;
}
}
while(ch==0);
a=a1;
b=b1;
printf("\nTo kleidi einai (%d,%d):\n",a,b);

printf("\nTo keimeno einai %s to mikos toy %d \n",str1,strlen(str1));
n=strlen(str1);

ek[n]='\0';
h=strlen(ek);
for (i=0; i<h; i++)
{
str1[i]=str1[i]-97;
ek[i]=((a*str1[i]+b)%26)+97;
printf("%c -> %d to \n",str1[i]+97,str1[i]);
}

printf("\n\nTo kriptografhmeno keimeno einai:%s \n",ek);
for (i=0; i<h; i++)
{
printf("%c -> %d \n",ek[i],ek[i]-97);
}
printf("To kriptografhmeno keimeno einai:%s \n\n",ek);

}



/*int n,i,h,a,b;
char str1[80],str2[80],ek[80];
printf("dwse to keimeno\n");
gets(str1);
printf("dwse to kleidi\na:");
scanf("%d",&a);
printf("\nb:");
scanf("%d",&b);
printf("\nto kleidi einai (%d,%d):\n",a,b);
i=0;
printf(" to keimeno einai %s to mikos toy %d \n",str1,strlen(str1));

n=strlen(str1);

printf("mhkos %d \n",n);
ek[n]='\0';
h=strlen(ek);
for (i=0; i<h; i++)
{
str1[i]=str1[i]-97;
ek[i]=((a*str1[i]+b)%26)+97;

printf("to %c %d %dto \n",str1[i],str1[i],h);


}
for (i=0; i<h; i++)
{printf("to %c %d to \n",ek[i],ek[i]-97);}
printf("to kriptografhmeno keimeno einai:%s \n",ek);
*/



[i]decryption

cpp code
#include<stdio.h>
#include<string.h>
void mul(int a1,int b1,int *d,int *x,int *y);
void main()
{
int ch,xx,a1,b1,a,b,c,d,d1[15],h,n,x,key,y,i=0;
char str1[80],dk[80];
printf("Dwse to keimeno\n");
gets(str1);
do
{
printf("Dwse to kleidi\na:");
scanf("%d",&a);
printf("\nb:");
scanf("%d",&b);

a1=a;
b1=b;
b=26;
mul(a,b,&d,&x,&y);
key=x;
if (key<0)
{
key=26+key;
}
printf("\n1/a:%d \n",key);

d=1;
while(d!=0)
{


c=a/b;

d=a%b;
d1=d;
a=b;
b=d;
i=i++;



}

n=i-1;





if(d1[n-1]==1)
{
printf("\nOi ariumoi einai prvtoi metaji tous\n\n");
ch=1;

}
else
{
printf("\nOi ariumoi den einai prvtoi metaji tous\n\n");
ch=0;
}
}
while(ch==0);
a=a1;
b=b1;
printf("\nTo kleidi einai (%d,%d):\n",a,b);

printf("\nTo keimeno einai %s to mikos toy %d \n",str1,strlen(str1));
n=strlen(str1);

dk[n]='\0';
h=strlen(dk);
for (i=0; i<h; i++)
{
str1[i]=str1[i]-97;
xx=(str1[i]-b)%26;/*to kano se periptosi pou o b einai megalos*/
if (xx<0)
{
xx=26+xx;
}

dk[i]=((key*(xx))%26)+97;
printf("%c -> %d\n",str1[i]+97,str1[i]);
}
printf("\n\nTo kriptografhmeno keimeno einai:%s \n",dk);
for (i=0; i<h; i++)
{
printf("%c -> %d\n",dk[i],dk[i]-97);
}
printf("To kriptografhmeno keimeno einai:%s \n\n",dk);

}

void mul(int a1,int b1,int *d1,int *x1,int *y1)
{int c,d,x,y;
if(b1==0)
{
*d1=a1;
*x1=1;
*y1=0;


}
else{
d=*d1;
x=*x1;
y=*y1;



c=a1%b1;

mul(b1,c,&d,&x,&y);


*d1=d;
*x1=y;
*y1=x-(a1/b1)*(y);

}

}



[i]gcd
cpp code
#include <stdio.h>

int euclid(int a,int b)
{
if(b==0)
return a;
else
return euclid(b,a%b);
}

int main()
{
int n1,n2;
printf("Enter two numbers to find its GCD:");
scanf("%d %d",&n1,&n2);
printf("The GCD of %d and %d is %d\n",n1,n2,euclid(n1,n2));
return 0;
}


well someone could think why i did two separate ways of affine encryption and decryption..
well if you find the way to add the missing lines on the code of ceasar you can find the answer for it ;))
it just needs the additions to make a ceaser cryptosystem to affine...
well looking forward to hear your thoughts..



Re: ascii codes using of it in c

Mon Jan 12, 2009 3:00 pm

and for those who are more interestead ill give you the ceasar code in another languages just to see the usage of ascii there ))
and this is printable ascii code usage..


pascall
pascal code
program shfrovalka;
uses crt;
var text:string;
m,k,c,men:integer;
procedure cez(var text:string; var k:integer);
begin
clrscr;
writeln('vvedite isxodniy text ');
write('$~/> ');
read(text);
write('vvedite klu4 shifrovani9 ');
readln(k);
for m:=1 to length(text) do
begin
c:=ord(text[m])+k;
if c>256 then c:=c-256;
text[m]:=chr(c);
end;
end;
procedure desh (var text:string);
begin
writeln('vvedite kluch deshifrovki' );
readln(k);
for m:=1 to length(text) do
begin
c:=ord(text[m])-k;
if c<256 then c:=c+256;
text[m]:=chr(c);
end;
end;
begin
repeat
clrscr;
writeln('1 - shifrovka ');
writeln('2 - deshifrovka ');
writeln('3 - sosto9nie texta ');
readln(men);
case men of
1:cez(text,k);
2:desh(text); U?
3:begin
writeln(text);
readkey;
end;
end;
until men = 0;
end.


in c++
pascal code
#include "stdafx.h"

void encode(char *input, char *output, int start); // шифрование
void decode(char *input, char *output, int start); // расшифровка

int main(int argc, char* argv[])
{
setlocale(LC_ALL, "rus");
if (argc!=5) {
cout << "Образец запуска: ";
cout << "cezar_ascii.exe encode/decode offset ";
cout << "input_file - имя входного файла ";
cout << "output_file - имя выходного файла ";
cout << "encode - зашифровать ";
cout << "decode - расшифровать ";
cout << "offset - величина смещения алфавита замены ";
exit(1);
}

for (unsigned int i=0; i
if (!isdigit(argv[4][i])) {
cout << "Величина смРом ";
exit(1);
}
}

if (toupper(*argv[3])=='E') {
encode(argv[1], argv[2], atoi(argv[4]));
} else { // иначе расшифровываем
decode(argv[1], argv[2], atoi(argv[4]));
}

return 0;
}

// шифрование
void encode(char *input,
char *output,
int start) {

ifstream in(input, ios::in | ios::binary);
ofstream out(output, ios::out | ios::binary);
try {
if (!in) {
cerr << "Не могу открыть входной файл. ";
exit(1);
}
if (!out) {
cerr << "Не могу открыть выходной файл. ";
in.close();
exit(1);
}

int ch; // для хранени го символа
do {
ch = in.get();
if (!in.eof()) {
ch += start;
if (ch>255) {
ch -= 255; // сдвиг циклический
}
out.put((char) ch);
}
} while (!in.eof());
} catch (char *errMess) { // если ошибка
cerr << errMess << endl;
if (in) {
in.close();
}
if (out) {
out.close();
}
}
// закрыть используемые файлы
if (in) {
in.close();
}
if (out) {
out.close();
}
}

// расшифровка
void decode(char *input, char *output, int start) {

ifstream in(input, ios::in | ios::binary);
ofstream out(output, ios::out | ios::binary);
try {
if (!in) {
cerr << "Не могу открыть входной файл. ";
exit(1);
}
if (!out) {
cerr << "Не могу открыть выходной файл. ";
in.close();
exit(1);
}

int ch; // для храÐ
do {
ch = in.get();
if (!in.eof()) { // признаÐ
ch -= start;
if (ch<0) {
ch += 255;
}
out.put((char) ch);
}
} while (!in.eof());
} catch (char *errMess) {
cerr << errMess << endl; // вывести сообщение об ошибке
if (in) {
in.close();
}
if (out) {
out.close();
}
}

// закрыть рание открытые файлы
if (in) {
in.close();
}
if (out) {
out.close();
}
}


in java
pascal code
// CaesarCipher

package ru.festu.u031.asanov.security.ref1;

public class CaesarCipher {

/** Зашифровать строку */

public static String encrypt(String s, int key) {

String result = "";

for(int i = 0; i < s.length(); i++) {

// зашифровать каждый символ в строке

result += encrypt(s.charAt(i), key);

}

return result;

}

/** Зашифровать отдельный символ */

public static char encrypt(char c, int key) {



if(c >= 'а' && c <= 'я') c = Character.toUpperCase(c);

// "повертуть" букву

if(c >= 'А' && c <= 'Я') c = rotate(c, key);

return c;

}

/** Расшифровать строку */

public static String decrypt(String s, int key) {



return encrypt(s, -key);

}

/** Расшифровать отдельный символ */

public static char decrypt(char c, int key) {

if(c < 'А' || c > 'Я') return c;

else return rotate(c, key);

}

/** "Поворот" символа */

private static char rotate(char c, int key) {

int l = 'Я' - 'А';

c += key % l;

if(c < 'А') c += l;

if(c > 'Я') c -= l;

return c;

}

}


well it s just the same code in multilanguage using this proves that by learning one you can slowly develop skills with the others....

Re: ascii codes using of it in c

Mon Jan 12, 2009 5:30 pm

Thank you so much for this :)

Post a reply
  Related Posts  to : ascii codes using of it in c
 Print the ASCII Set     -  
 few examples of c using ascii     -  
 codes for encryption/decryption algorithms     -  
 Unicode, ASCII, UTF-16, and UTF-8 characters in java     -  
 cpu priority scheduling in java---codes please..     -  
 PHP forum- images displaying as codes     -  
 images,videos and signatures displaying as codes     -  
 How to save in a file the ASCII Characters? Like "☺"     -  

Topic Tags

C++ Basics