ROT13 Encrypter/Decrypter

Stato
Discussione chiusa ad ulteriori risposte.

Robertof

Utente Silver
19 Giugno 2008
186
10
0
98
Sono qui per presentarvi un altro esercizio di programmazione, sempre by me xD.
L'esercizio è QUASI uguale al precedente, si usano sempre le posizioni delle lettere dell'alfabeto ma in modo diverso.
E' simile al Cifrario di Cesare, ma il cifrario di Cesare fa avanzare la posizione delle lettere di +3, mentre questo di +13 (da cui deriva anche il nome ROT13).
Questo esercizio prevede di fare un encrypter/decrypter di ROT13 e postare sempre nel tag off topic il seguente testo criptato:
Codice:
Ciao, se sei riuscito a criptare questo testo con successo, significa che hai compiuto con successo l'esercizio. Ottimo!
Lo script deve inoltre rimuovere qualsiasi carattere speciale, deve convertire la frase in minuscolo e deve rimuovere tutti gli spazi. Il risultato della funzione di encrypt è una stringa in maiuscolo e senza spazi, mentre nella funzione decrypt il risultato è la stringa criptata (se avete scritto bene la funzione di encrypt la funzione di decrypt vi restituirà la stringa criptata senza spazi e tutta in minuscolo).

Soluzione in PHP (Non sbirciate finché non avete finito il vostro, altrimenti non vale):
[ot]
PHP:
/* ROT-13 Encrypter */
$alpha = str_split('abcdefghijklmnopqrstuvwxyz',1);
function encode_rot13($string) {
	global $alpha;
	$keys = array();
	for ($i = 0;$i < count($alpha); $i++) {
		if ($i >= 13) {$sx = $i-13;}else{$sx = $i+13;}
		$keys[$alpha[$i]] = $alpha[($sx)];
	}
	$string = strtolower($string);
	$banned=explode("X","!X\"X£X\$X%X&X/X(X)X?X'XìX^X0X1X23X4X5X6X7X8X9X@XòXçX#XàX°XùX§X*X+X]X}XèX[X{XéX,X;X.X:X-X_X<X>X|X ");
    $string = str_replace($banned,'',$string);
	$str = '';
	for ($i=0;$i<strlen($string);$i++) {
		$str .= $keys[$string[$i]];
	}
	return strtoupper($str);
}

function decode_rot13($encrypted) {
	global $alpha;
	$keys = array();
	for ($i=0;$i<count($alpha);$i++) {
		if ($i >= 13) {$sx = $i-13;}else{$sx = $i+13;}
		$keys[$alpha[$sx]] = $alpha[$i];
	}
	$encrypted = strtolower($encrypted);
	$ret = '';
	for ($i=0;$i<strlen($encrypted);$i++)
		$ret .= $keys[$encrypted[$i]];
	return $ret;
}
[/ot]

Ulteriori informazioni sull'algoritmo ROT13

Happy coding!
 
Robertof ha detto:
e postare sempre nel tag off topic il seguente testo criptato:
Codice:
Ciao, se sei riuscito a criptare questo testo con successo, significa che hai compiuto con successo l'esercizio. Ottimo!

Edit: e la funzione di decrypt?
 
Codice:
/* Author: Jcjh
   License: GPLv3
*/

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

char *
getline ()
{
  char *buff = NULL;
  char c;
  int s = 1;
  int not_void = 0;

  while ((c = getchar ()) != '\n')
    {
      not_void = 1;
      buff = (char *) realloc (buff, s + 1);
      buff[s - 1] = c;
      buff[s] = 0x00;
      s++;
    }
  return (not_void) ? buff : NULL;
}

int
main ()
{

  char *string = getline ();
  int len = strlen (string), c;

  for (c = 0; c < len; c++)
    {
      if (((string[c] < 65) || (string[c] > 90))
	  && ((string[c] < 96) || (string[c] > 122)))
	string[c] = ' ';

      if ((string[c] > 92) && (string[c] < 123))
	string[c] -= 32;

      if (string[c] != ' ')
	{
	  if (string[c] < 78)
	    string[c] += 13;
	  else
	    string[c] -= 13;

	}
    }

  printf ("%s\n", string);
  return 0;
}

crypt
[OT]FR FRV EVHFPVGB N PEVCGNER DHRFGB GRFGB PBA FHPPRFFB FVTAVSVPN PUR UNV PBZCVHGB PBA FHPPRFFB Y RFREPVMVB BGGVZB [/OT]

decrypt
[OT]SE SEI RIUSCITO A CRIPTARE QUESTO TESTO CON SUCCESSO SIGNIFICA CHE HAI COMPIUTO CON SUCCESSO L ESERCIZIO OTTIMO[/OT]
 
eccolo il mio in c++ finalmente...XD

decriptare:
Codice:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
     
     
int main()
{
    int y , z;
    char x[y]; 
       cout << "Inserisci Una Stringa Da Decriptare\n";
       gets(x);
       for (y=0; y<=strlen(x)-1; y++) {
            z = (int) x[y];
            if ((z>=65 && z<=90) || (z>=97 && z<=122)) cout << "";
            else cout << "non valido!\n" ;
                               }
         for (y=0; y<=strlen(x)-1; y++) {
           x[y]=x[y] | 32;     //volge la stringa al minuscolo, disattivando il sesto bit
           z = (int)x[y]-97;
           z -= 13;
           if (z<0) z+=26;
             x[y] = (char)z + 97;
             }
        cout << "La Stringa E' Diventata:\n" << x << endl;
        
    
    return 0;
}

criptare:
Codice:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
     
     
int main()
{
    int y , z;
    char x[y]; 
       cout << "Inserisci Una Stringa Da Criptare\n";
       gets(x);
       for (y=0; y<=strlen(x)-1; y++) {
            z = (int) x[y];
            if ((z>=65 && z<=90) || (z>=97 && z<=122)) cout << "";
            else cout << "non valido!\n" ;
                               }
         for (y=0; y<=strlen(x)-1; y++) {
           x[y]=x[y] | 32;     //volge la stringa al minuscolo, disattivando il sesto bit
           z = (int)x[y]-97;
           z += 13;
           if (z>=27) z=z-26;
             x[y] = (char)z + 97;
             }
        cout << "La Stringa E' Diventata:\n" << x << endl;
        
    
    return 0;
}

[ot]pvnb fr frv evhfpvgb n pevcgner dhrfgb grfgb pba fhpprffb fvtavsvpn pur unv pbzcvhgb pba fhpprffb y rfrepvmvb bggvzb [/ot]
 
[Python]
Codice:
#!/usr/bin/python
def crypt(string):
    letters=list('abcdefghijklmnopqrstuvwxyz')
    global crypt
    crypt=[]
    string=string.lower()
    for i in string:
        if i==" ":
            crypt.append(" ")
            continue
        for j in xrange(0, len(letters)):
            if i==letters[j]:
                global tot
                tot=j+13
                if tot>len(letters)-j:
                    tot=tot-len(letters)
                crypt.append(letters[tot])
                break
    return ''.join(crypt)
def decrypt(string):
    letters=list('abcdefghijklmnopqrstuvwxyz')
    global crypt
    crypt=[]
    string=string.lower()
    for i in string:
        if i==" ":
            crypt.append(" ")
            continue
        for j in xrange(0, len(letters)):
            if i==letters[j]:
                global tot
                tot=j-13
                if tot>len(letters)-j:
                    tot=tot-len(letters)
                crypt.append(letters[tot])
                break
    return ''.join(crypt)
func=raw_input("Crypt o decrypt: ")
func.lower()
word=raw_input("Inserisci la parola: ")
if func=="crypt":
    print crypt(word)
elif func=="decrypt":
    print decrypt(word)
else:
    print "Funzione inesistente!"
 
Robertof ha detto:
Sono qui per presentarvi un altro esercizio di programmazione, sempre by me xD.
L'esercizio è QUASI uguale al precedente, si usano sempre le posizioni delle lettere dell'alfabeto ma in modo diverso.
E' simile al Cifrario di Cesare, ma il cifrario di Cesare fa avanzare la posizione delle lettere di +3, mentre questo di +13 (da cui deriva anche il nome ROT13).
Questo esercizio prevede di fare un encrypter/decrypter di ROT13 e postare sempre nel tag off topic il seguente testo criptato:
Codice:
Ciao, se sei riuscito a criptare questo testo con successo, significa che hai compiuto con successo l'esercizio. Ottimo!
Lo script deve inoltre rimuovere qualsiasi carattere speciale, deve convertire la frase in minuscolo e deve rimuovere tutti gli spazi. Il risultato della funzione di encrypt è una stringa in maiuscolo, mentre nella funzione decrypt il risultato è la stringa criptata (se avete scritto bene la funzione di encrypt la funzione di decrypt vi restituirà la stringa criptata senza spazi e tutta in minuscolo).

Soluzione in PHP (Non sbirciate finché non avete finito il vostro, altrimenti non vale):
[ot]
PHP:
/* ROT-13 Encrypter */
$alpha = str_split('abcdefghijklmnopqrstuvwxyz',1);
function encode_rot13($string) {
	global $alpha;
	$keys = array();
	for ($i = 0;$i < count($alpha); $i++) {
		if ($i >= 13) {$sx = $i-13;}else{$sx = $i+13;}
		$keys[$alpha[$i]] = $alpha[($sx)];
	}
	$string = strtolower($string);
	$banned=explode("X","!X\"X£X\$X%X&X/X(X)X?X'XìX^X0X1X23X4X5X6X7X8X9X@XòXçX#XàX°XùX§X*X+X]X}XèX[X{XéX,X;X.X:X-X_X<X>X|X ");
    $string = str_replace($banned,'',$string);
	$str = '';
	for ($i=0;$i<strlen($string);$i++) {
		$str .= $keys[$string[$i]];
	}
	return strtoupper($str);
}

function decode_rot13($encrypted) {
	global $alpha;
	$keys = array();
	for ($i=0;$i<count($alpha);$i++) {
		if ($i >= 13) {$sx = $i-13;}else{$sx = $i+13;}
		$keys[$alpha[$sx]] = $alpha[$i];
	}
	$encrypted = strtolower($encrypted);
	$ret = '';
	for ($i=0;$i<strlen($encrypted);$i++)
		$ret .= $keys[$encrypted[$i]];
	return $ret;
}
[/ot]

Ulteriori informazioni sull'algoritmo ROT13

Happy coding!
 
Quando si cripta la stringa dev'essere in maiuscolo, quando si decripta in minuscolo.
Ottimo a tutti quanti comunque ^_^
@Jcjh: Ti sei dimenticato di criptare/decriptare il "ciao", comunque la stringa criptata/decriptata non deve avere spazi;)
@lepa: Anche a te la stringa criptata / decriptata non deve avere spazi ;)
 
Codice:
def encrypt (string) string.gsub(/[^A-z ]/, '').upcase.tr('[A-Z]', '[N-ZA-M]') end
def decrypt (string) string.tr('[A-Z]', '[N-ZA-M]').downcase end
[ot]
PVNB FR FRV EVHFPVGB N PEVCGNER DHRFGB GRFGB PBA FHPPRFFB FVTAVSVPN PUR UNV PBZCVHGB PBA FHPPRFFB YRFREPVMVB BGGVZB
ciao se sei riuscito a criptare questo testo con successo significa che hai compiuto con successo lesercizio ottimo
[/ot]
 
scusate... Ma non capisco... in ROT13 (se si usa l'alfabeto inglese) la funzione di decrypt è identica a quella di encrypt... Perchè avete fatto tutti due funzioni quando ne bastava una...
c++
Codice:
  string encdec(string str){
    string x;
    for (int i=0; i<str.size(); i++){
        if (str[i]>='A' && str[i]<'A'+13) x.push_back(str[i]+13);
        else if(str[i]>='A'+13 && str[i]<'A'+26) x.push_back(str[i]-13);
        else if (str[i] == ' ');
        else return "Error";
    }
    return x;
}
Ovviamente questa funziona solo se inserite stringhe interamente maiuscole ma non ci vuole un genio per far sì che funzioni con tutte le stringhe...
 
il mio in java:
Codice:
public class Rot13{
    public void Decrypt(String st){
        String an="abcdefghijklmnopqrstuvwxyz";
        String sfin="";
        st=st.toLowerCase();
        for(int i=0;i<st.length();i++){
           if('a' <= st.charAt(i) && st.charAt(i) <= 'z'){
               int v=(""+st.charAt(i)).hashCode()-110;
               if(v<0) v+=26; 
               sfin+=""+an.charAt(v);
           }
        }System.out.println(sfin);
    }
    public void Crypt(String st){
        String ac=" NOPQRSTUVWXYZABCDEFGHIJKLM";
        st=st.toLowerCase();
        String sfin="";
        for(int i=0;i<st.length();i++){ 
            if('a' <= st.charAt(i) && st.charAt(i) <= 'z'){
                sfin+=ac.charAt((""+st.charAt(i)).hashCode()-96);
            }else if(st.charAt(i)==' '){
                sfin+=" ";   
            }
        }System.out.println(sfin);
    }
}
risulati:
[ot]
Crypt:
input:
Codice:
Ciao, se sei riuscito a criptare questo testo con successo, significa che hai compiuto con successo l'esercizio. Ottimo!
output:
Codice:
PVNB FR FRV EVHFPVGB N PEVCGNER DHRFGB GRFGB PBA FHPPRFFB FVTAVSVPN PUR UNV PBZCVHGB PBA FHPPRFFB YRFREPVMVB BGGVZB

Decrypt:
input:
Codice:
PVNB FR FRV EVHFPVGB N PEVCGNER DHRFGB GRFGB PBA FHPPRFFB FVTAVSVPN PUR UNV PBZCVHGB PBA FHPPRFFB YRFREPVMVB BGGVZB
output:
Codice:
ciaoseseiriuscitoacriptarequestotestoconsuccessosignificachehaicompiutoconsuccessolesercizioottimo
[/ot]
 
solo ha detto:
scusate... Ma non capisco... in ROT13 (se si usa l'alfabeto inglese) la funzione di decrypt è identica a quella di encrypt... Perchè avete fatto tutti due funzioni quando ne bastava una...
c++
Codice:
  string encdec(string str){
    string x;
    for (int i=0; i<str.size(); i++){
        if (str[i]>='A' && str[i]<'A'+13) x.push_back(str[i]+13);
        else if(str[i]>='A'+13 && str[i]<'A'+26) x.push_back(str[i]-13);
        else if (str[i] == ' ');
        else return "Error";
    }
    return x;
}
Ovviamente questa funziona solo se inserite stringhe interamente maiuscole ma non ci vuole un genio per far sì che funzioni con tutte le stringhe...

Perche' la sua strana richiesta chiede che il decrypt abbia un output differente rispetto all'encrypt, non chiedermi perche'.
 
Al diavolo i caratteri maiuscoli e minuscoli, gli output sono tutti in minuscolo.
PHP:
<?php
class rot13 {
	public $str;
	public $r;
	public function __construct($str) {
		$str = strtolower($str);
		for($i=0;$i<strlen($str);$i++)
			if(ord($str[$i]) >= 97 && ord($str[$i]) <= 122)
				$r .= $str[$i];
		$this->str = $r;
	}
	public function cript() {
		for($i=0;$i<strlen($this->str);$i++)
			if((ord($this->str[$i]) + 13) <= 122)
				$this->r .= chr(ord($this->str[$i]) + 13);
			else
				$this->r .= chr(96 + (13 - (122 - ord($this->str[$i]))));
		return $this->r;
	}
	public function decript() {
		for($i=0;$i<strlen($this->str);$i++)
			if((ord($this->str[$i]) - 13) >= 97)
				$this->r .= chr(ord($this->str[$i]) - 13);
			else
				$this->r .= chr(122 - (13 - (ord($this->str[$i]) - 96)));
		return $this->r;
	}
}
?>
 
lol _Wizard
perl: http://sprunge.us/bgBJ?pl
C: http://sprunge.us/CMcj
@Robertof: così va bene?
Codice:
shura@eeepc ~ $ ./rot13
PVNBFRFRVEVHFPVGBNPEVCGNERDHRFGBGRFGBPBAFHPPRFFBFVTAVSVPNPURUNVPBZCVHGBPBAFHPPRFFBYRFREPVMVBBGGVZB
ciaoseseiriuscitoacriptarequestotestoconsuccessosignificachehaicompiutoconsuccessolesercizioottimo
P.S.: Robertof il tuo fa davvero schifo però, usa le regex...:S, non prenderla come offesa :)

Edit: _Wizard vedi QUI, funziona? (non l'ho testata)
 
Stato
Discussione chiusa ad ulteriori risposte.