Linux slogan
Visite também: BR-Linux.org · Dicas-L · NoticiasLinux · SoftwareLivre.org · UnderLinux · BestLinux
» Screenshot
Linux: Kde icones Crystal clear suspekaramba
Por waplinux



» Login
Login:
Senha:

Se você ainda não possui uma conta, clique aqui.

Esqueci minha senha

» Wallpaper
Linux: Linux
Por cavera


Scripts

Linux user

Publicado por Orlando Xavier em (última atualização em 20/01/2010)   [ 1553 hits ]

Login: orlandoxavier, 9408 pontos

Homepage: www.orlandoxavier.org   


Descrição
Bem, estava lendo um artigo do Prof. Elgio aqui no VOL que tem como título: "Introdução a Criptografia". Para quem quiser conferir: http://www.vivaolinux.com.br/artigo/Introducao-a-criptografia/

Nele vi uma simples criptografia que é chamada de "Cifra de César". Resolvi botar a mesma em prática. Segue o script.

Abraço.

[ Download: cripto_cesar.c ]   [ Enviar nova versão ]

[ Esconder código-fonte ]

//      cripto_cesar.c
//      
//      Copyright 2010 Orlando Xavier <ox@orlandoxavier.org>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//      
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void encrypt(void);
void uncrypt(void);
void lowercase(char string[]);
void clear(void) { system("clear"); }
void getch(void) { system("read key"); }
int main(int argc, char** argv) {
   
   int menu = 0;
   
   do {
      printf("\n\nEnter para Continuar: \n");
      getch();
      clear();
      printf("+----------------------------+\n");
      printf("|;.<<,y7= Cesar-Crypto +;-,~^|\n");
      printf("+--------------+-------------+\n");
      printf("|&.6,+---------+--------+`~{,|\n");
      printf("|*[3,|  (1) - Encrypt   |,.çz|\n");
      printf("|;5m.+---------+--------+[k/;|\n");
      printf("|,'.;+---------+--------+.7.,|\n");
      printf("|}1>i|  (2) - uncrypt   |'^,>|\n");
      printf("|^f,;+---------+--------+,j.'|\n");
      printf("|&];.+---------+--------+x~};|\n");
      printf("|.4-a|  (3) - Exit      |'.,!|\n");
      printf("+----+------------------+----+\n");
      printf("Escolha uma opcao: ");
      scanf("%d",&menu);
      switch (menu) {
         case 1:
            encrypt();
            break;
         case 2:
            uncrypt();
         break;
      }
   } while (menu != 3);
   return(0);
}

void encrypt(void) {
   char string[255];
   int i = 0;
   
   clear();
   printf("Entre com a palavra: ");
   gets(string);
   gets(string);
   lowercase(string);
   for (; string[i] != '{FONTE}'; i++) {
      if (string[i] == 'z')
         string[i] = 'c';
      else if (string[i] == 'y')
         string[i] = 'b';
      else if (string[i] == 'x')
         string[i] = 'a';
      else
         string[i] = string[i] + 3;
   }
   printf("Resultado >> ");
   for (i = 0; string[i] != '{FONTE}'; i++) {
      printf("%c",string[i]);
   }
}

void uncrypt(void) {
   char string[255];
   int i = 0;
   
   clear();
   printf("Entre com a sequencia: ");   
   gets(string);
   gets(string);
   lowercase(string);
   for (; string[i] != '{FONTE}'; i++) {
      if (string[i] == 'c')
         string[i] = 'z';
      else if (string[i] == 'b')
         string[i] = 'y';
      else if (string[i] == 'a')
         string[i] = 'x';
      else
         string[i] = string[i] - 3;
   }
   printf("Resultado >> ");
   for (i = 0; string[i] != '{FONTE}'; i++) {
      printf("%c",string[i]);
   }
}

void lowercase(char string[])
{
   int  i = 0;

   while (string[i]) {
      string[i] = tolower(string[i]);
      i++;
   }

   return;
}

Scripts recomendados
   Script Linux recomendado Potências de 2
   Script Linux recomendado Métodos de Ordenação - Quick Sort
   Script Linux recomendado Desenhando Nuvens ou o Fractal de Plasma
   Script Linux recomendado Função Hash básica
   Script Linux recomendado Método eficiente de armazenamento utilizando containers (Vector e Map)

Comentários
[1] Comentário enviado por rodrigozanuzzo em 20/01/2010 - 13:42h:

Muito bom, parabéns.

[2] Comentário enviado por elgio em 20/01/2010 - 20:40h:

Falha se na string tiver espaços em branco, vírgulas ou pontos!

// Criptar
...// etapa para ler a string
/* somente esta laco basta, sem os tantos ifs e SEM PRECISAR o lowercase.. */
for (i=0; string[i]; i++) {
if ((string[i] >= 'a')&&(string[i] <= 'z')){
strings[i] = 'a' + ((string[i] - 'a' + 3) % 26);
}
if ((string[i] >= 'A')&&(string[i] <= 'Z')){
strings[i] = 'A' + ((string[i] - 'A' + 3) % 26);
}
}
printf ("resultado = %s\n", string);
}

testa e me diz ;-)

Ah, e sugiro mesmo que esqueças o gets. Sérios problemas com esta função (não viste o enorme aviso do compilador? hehehe): http://www.vivaolinux.com.br/artigo/Parametros-interessantes-do-scanf-e-do-printf-em-C e http://www.vivaolinux.com.br/script/Lendo-strings-em-C

[3] Comentário enviado por elgio em 20/01/2010 - 21:00h:

#include <stdio.h>

int cesar(char s[], char flag)
{
/* Flag = 'C' criptar
'D' = decriptar
*/

int i, k = 3;;

if (flag == 'D')
k = -3;

for (i = 0; s[i]; i++) {
if ((s[i] >= 'a')
&& (s[i] <= 'z')) {
s[i] = 'a' + ((s[i] - 'a' + k) % 26);
}
if ((s[i] >= 'A')
&& (s[i] <= 'Z')) {
s[i] = 'A' + ((s[i] - 'A' + k) % 26);
}
}
}

int main()
{
char s[200];

printf("Digite uma string com ate 200 cars:\n");

scanf("%200[^\n]s", s);
cesar(s, 'C');
printf("A string digitada cifrada por cesar fica: %s\n", s);

cesar(s, 'D');
printf("Decifrada fica: %s\n", s);
}

[4] Comentário enviado por orlandoxavier em 22/01/2010 - 12:05h:

Muito obrigado, Prof. Elgio.
Abraços.


Contribuir com comentário
  
Para executar esta ação você precisa estar logado no site, caso contrário, tudo o que for digitado será perdido.
Responsável pelo site: Fábio Berbert de Paula - Copyleft 2002-2009 Viva o Linux.com.br

Viva o Linux

A maior comunidade Linux da América Latina! Artigos, dicas, tutoriais, fórum, scripts e muito mais. Ideal para quem busca auto-ajuda em Linux.