Total members 9950 | Gratitudes |It is currently Sat Feb 11, 2012 3:16 am Login / Join Codemiles


All times are UTC [ DST ]




Post new topic Reply to topic  Quick reply  [ 3 posts ] 
Author Question
 Question subject: ascii codes using of it in c
PostPosted: Mon Jan 12, 2009 2:00 pm 
Offline
Moderator
User avatar

Joined: Fri Nov 21, 2008 6:18 pm
Posts: 51
Location: thessaloniki
Has thanked: 0 time
Have thanks: 2 time

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
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[i] != '\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;
}



affine encryption

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[i]=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);
*/




decryption

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[i]=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);

   }
   
}





gcd
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..

_________________
if you want make an effort yourself no one will make it for you...
best regards


TOP
 Profile Send private message  
Reply with quote  
 Question subject: Re: ascii codes using of it in c
PostPosted: Mon Jan 12, 2009 3:00 pm 
Offline
Moderator
User avatar

Joined: Fri Nov 21, 2008 6:18 pm
Posts: 51
Location: thessaloniki
Has thanked: 0 time
Have thanks: 2 time
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
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++
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') {  // 3-им параметром в командной строке задано Encode - зашифровываем
    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; // производим сдвиг на заданную величину по таблице кодов ASCII
        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
Code:
1.1. Шифр Цезаря

Шифр Цезаря основан на фиксированном смещении по кругу букв алфавита. Буквы сдвигаются по кругу, так что после последней буквы алфавита идет его первая буква. В следующем листинге (на языке java) приводится алгоритм шифрования на основе шифра Цезаря.

Листинг 1. класс 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....

_________________
if you want make an effort yourself no one will make it for you...
best regards


TOP
 Profile Send private message  
Reply with quote  
 Question subject: Re: ascii codes using of it in c
PostPosted: Mon Jan 12, 2009 5:30 pm 
Offline
Mastermind
User avatar

Joined: Tue Mar 27, 2007 10:55 pm
Posts: 2103
Location: Earth
Has thanked: 39 time
Have thanks: 56 time
Thank you so much for this :)

_________________
Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )


TOP
 Profile Send private message  
Reply with quote  
Post new topic Reply to topic Quick reply  [ 3 posts ] 
Quick reply


  


 Similar topics
 Topic title   Forum   Author   Comments 
 html codes  Java  Anonymous  2
 images,videos and signatures displaying as codes  PHP  finsnfish  3
 PHP forum- images displaying as codes  PHP  finsnfish  0
 few examples of c using ascii  C-C++  biskot188  1
 urgent help from any one exp in c++ i need codes  C-C++  computer_science  3

All times are UTC [ DST ]


Users browsing similar posts

Users browsing this forum: No registered users and 2 guests



Jump to:  
Previous Question | Next Question 




Home
General Talks
Finished Projects
Code Library
Games
Tutorials

Java
C/C++
C-sharp
php
Script
JSP/Servlets
Ajax
ASP/ASP.net
Google SEO
Database
Communications
Phpbb3 styles
Photoshop tutorials
Flash tutorials
Find a job






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team