Sonntag, 24. Oktober 2010

kleine Idee: Caesar-Verschlüsselung Klasse

public class CeasarCyphre
{
   private char[][] cy_ar;
   private int offset;

private void createCodeTable()
{
   int i = 97;

   for(int j = 0; j < cy_ar[0].length; j++)
   {
    cy_ar[0][j] = (char)i++;
   }
   i = 97 + offset;

   for(int j = 0; j < cy_ar[0].length; j++)
   {
    if(i > 122)
     i = 97;

    cy_ar[1][j] = (char)i++;
   }
}

public CeasarCyphre(int offset)
{
   cy_ar = new char[2][26];
   this.offset = offset;
   createCodeTable();
}

public String decrypt(String str)
{
   boolean found = false;
   String result = "";

   str = str.toLowerCase();

   for(int i = 0; i < str.length(); i++)
   {
    for(int j = 0; j < cy_ar[0].length && !found; j++)
    {
     if(cy_ar[1][j] == str.charAt(i))
    {
      result += cy_ar[0][j];
      found = true;
    }

   }
   found = false;
  }

   return result;
}

public String encrypt(String str)
{
   String result = "";
   boolean isencrypt = false;

   str = str.toLowerCase();

   for(int i = 0; i < str.length(); i++)
   {
    for(int j = 0; j < cy_ar[0].length && !isencrypt; j++)
    {
     if(cy_ar[0][j] == str.charAt(i))
     {
      isencrypt = true;
      result += cy_ar[1][j];
     }
    }
     isencrypt = false;
    }

   return result;
}
}

Eine einfache Klasse zum Verschlüsseln und Entschlüsseln von Strings in Caesar-Verschlüsselung. Sie ist nicht unbedingt die effizienteste Klasse aber funktioniert mit jedem zusammenhängenden String ohne Sonderzeichen. Die Klasse ist in Java geschrieben. Wie immer übernehme ich keine Funktionsgarantie, d.h. Verwendung auf eigene Verantwortung.

Keine Kommentare:

Kommentar veröffentlichen