Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Beschreiben Sie hier die Klasse main.
- *
- * @author (Ihr Name)
- * @version (eine Versionsnummer oder ein Datum)
- */
- public class matrixRaster
- {
- public static void main(String[] args)
- {
- System.out.println("Encrypted: " + encrypt("ICHBINDERDOKTOREISENBART",6));
- System.out.println("--------------------------------------------------");
- System.out.println("Decrypted: " + decrypt("IDTECEONHRRBBDEAIOIRNKST ", 6));
- }
- private static String encrypt(String pText, int encryptionKey)
- {
- //Initialize String Builder to build encrypted String
- StringBuilder sb = new StringBuilder();
- //calculate rows on encryptionKey (+1 if text length is not divisible by encryptionKey)
- int zeile = (pText.length()%encryptionKey == 0 ? pText.length()/encryptionKey : pText.length()/encryptionKey+1),
- spalte = encryptionKey;
- //Create matrix according to columns and rows
- char[][] matrix = new char[zeile][spalte];
- //fill matrix
- for(int i = 0; i < zeile; i++)
- {
- for(int j = 0; j < spalte; j++)
- {
- //fill first letter of string into matrix
- matrix[i][j] = pText.charAt(0);
- //can't fill the matrix with no characters left.
- if(pText.length() <= 1)break;
- //remove first letter of string
- pText = pText.substring(1);
- }
- }
- //print matrix
- System.out.println("Matrix: ");
- printMatrix(matrix);
- //read matrix from top to bottom to build encrypted string
- for(int i = 0; i < spalte; i++)
- {
- for(int j = 0; j < zeile; j++)
- {
- sb.append(matrix[j][i]);
- }
- }
- System.out.println();
- //return encrypted String
- return sb.toString();
- }
- private static String decrypt(String pText, int decryptionKey)
- {
- //when swapping columns with rows while encrypting an already encrypted string, it actually decrypts said string
- return encrypt(pText,(pText.length()/decryptionKey));
- }
- private static void printMatrix(char[][] matrix)
- {
- for(int i = 0; i < matrix.length; i++)
- {
- for(int j = 0; j < matrix[i].length; j++)
- System.out.print(matrix[i][j]);
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement