Codage en hillcypher

Contenu du snippet

Ce code fait le codage d'une chaine de deux caractères mais vous pouvez augmenT la dimension de la chaine en changeant DIMENSION et CYPHER_HILL par une clé matricielle "e" (Dfinit dans une variable private au Dbut de la classe voir code)

Source / Exemple :


package javafr;

import java.lang.Exception;

/**
 *

  • @author scupper
  • @since 16:33 March 23rd 2011
*
  • /
public class CodeHill { private static int[][] HILL_KEY={{3,6}, {1,5}}; //faudrait que pgcd(det(HILL_KEY), 26) = 1 private static int DIMENSION = 2; public int getDimension(){ return this.DIMENSION; } public void setDimension(int dimension){ this.DIMENSION=dimension; } public void setKey(int[][] key) throws Exception{ boolean bool = true; for(int i=0;i<this.DIMENSION;i++){ bool = bool & ((key[i].length==this.DIMENSION)?true:false); } if(key.length != this.DIMENSION && bool){ throw new Exception("Error : Bad Array Initialisation"); }else{ for(int i =0; i<2;i++){ for(int j =0;j<2;j++){ this.HILL_KEY[i][j]=key[i][j]; } } } } public int[][] getKey(){ int[][] key = new int[2][2]; for(int i =0; i<2;i++){ for(int j =0;j<2;j++){ key[i][j]=this.HILL_KEY[i][j]; } } return key; } public StringBuffer cypher(StringBuffer str,int[][] key,int dimension){ StringBuffer s = new StringBuffer(); char c; setDimension(dimension); int[][] nKey = new int[this.DIMENSION][this.DIMENSION]; for(int i=0;i<key.length;i++){ for(int j =0;j<key[i].length;j++){ nKey[i][j]=key[i][j]%26; } } try { setKey(nKey); } catch (Exception ex) { System.out.println(ex.getMessage()); System.exit(this.DIMENSION); } StringBuffer nStr=new StringBuffer(str.toString().toUpperCase()); if(str.length()!=this.DIMENSION){ try { throw new Exception("Error : the String Length should be : " + this.DIMENSION); } catch (Exception ex) { System.out.println(ex.getMessage()); System.exit(DIMENSION); } } int[] code = new int[this.DIMENSION]; for(int i =0;i<this.DIMENSION;i++){ int cod = 0; for(int j = 0;j<this.DIMENSION;j++){ c = nStr.charAt(j); cod +=(((int)c - 65) * nKey[j][i]); } cod = (cod%26)+65; code[i] = cod; s.append((char)code[i]); } return s; } public static void main(String[] args){ CodeHill obj = new CodeHill(); for(int i =0;i<DIMENSION;i++){ System.out.println(obj.cypher( new StringBuffer("MO"), HILL_KEY,2)); } } }

Conclusion :


pour le cas de DMENSION =2 on a pour le e spécifier

run:
YM
YM
BUILD SUCCESSFUL (total time: 1 second)

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.