Xifra de Vigenère





-8
Date Submitted Wed. Oct. 11th, 2006 7:04 AM
Revision 1 of 1
Beginner toriwells
Tags criptography | divertimento | Java
Comments 1 comments
Classe que pren una frase i una clau i obté com a sortida el missatge encriptat usant l'algorisme de Vigenère.


/**
* El programa obté el text i la clau, elimina els espais i els passa a majúscules.
* No té en compte caràcters especials (ç, ñ, tildes, etc...). És barruer i es
* podria fer millor... però aquesta no és una classe de metodologia de programació, no? ;)
*/

package blog.crypto;

public class Vigenere {

    private String eliminarEspais( String st ) {
        String _st = new String();
        for (int i = 0; i < st.length(); i++) {
            if ( st.charAt(i) != ' ' ) {
                _st += st.charAt(i)+"";
            }
        }
        return _st;
    }
   
    private void execute( String text , String clau ) throws Exception {
        char[] _text = new char[ text.length() ];
        char[] _clau = new char[ _text.length ];
       
        //xifrem el missatge
        for ( int i = 0 ; i < text.length() ; i++ ) {
            char t = text.charAt(i);
            char c = clau.charAt( i % clau.length() );
           
            int aux = (int)t;
            int aux2 = (int)c;
            aux -= 65;
            aux2 -= 65;
           
            _text[i] = (char)(((aux + aux2) % 26) + 65);
        }
       
        System.out.println("Missatge: " + text);
        System.out.println("Clau: " + clau);
        System.out.print("Criptograma: ");
       
        for (int i = 0; i < _text.length; i++) {
            System.out.print(""+_text[i]);
        }
       
    }
   
    /**
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Vigenere v = new Vigenere();
        try {
            if ( args.length != 2 ) {
                System.out.println("Ús: java blog.crypto.Vigenere \"text\" clau");
                System.exit(0);
            }
            v.execute( v.eliminarEspais(args[0]).toUpperCase(), v.eliminarEspais(args[1]).toUpperCase() );
        }
        catch ( Exception ex ) {
            System.out.println("ERROR:: " + ex.toString());
        }

    }

}

 

Ramon Maria Gallart

Comments

Comments WTF
Thu. Jan. 4th, 2007 3:54 AM    Beginner SurfMan

Voting