Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.Scanner;
- public class Main {
- public static String message;
- public static String key;
- public static int min,max;
- public static StringBuilder encrypted = new StringBuilder();
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- getInput(sc);
- testForKeyLength();
- testForRepeatingNumbers();
- message = addIntervalsIfNeeded(message);
- min = getMin();
- max = getMax();
- int i = 0, j=8;
- String block;
- while(true){
- try {
- block = message.substring(i, j);
- } catch(IndexOutOfBoundsException e){
- break;
- }
- i += 8;
- j += 8;
- for(int y=0; y<block.length(); y++) {
- int index = getIndex((char) min);
- encrypted.append(block.charAt(index));
- min++;
- if(min>max){
- min= getMin();
- }
- }
- }
- System.out.println(encrypted.toString());
- }
- private static void getInput(Scanner sc) {
- System.out.println("Enter message:");
- message = sc.nextLine();
- System.out.println("Enter key:");
- key = sc.nextLine();
- }
- private static void testForKeyLength() {
- if(key.length() != 8){
- System.out.println("ERROR KEY MUST BE 8 SYMBOLS!");
- System.exit(0);
- }
- }
- private static void testForRepeatingNumbers() {
- LinkedHashMap<Character,Integer> map = new LinkedHashMap<Character,Integer>();
- for(char ch: key.toCharArray()){
- if(map.containsKey(ch)){
- map.put(ch,map.get(ch)+1);
- continue;
- }
- map.put(ch,1);
- }
- for(Map.Entry<Character,Integer> entry : map.entrySet()){
- if(entry.getValue()>=2){
- System.out.println("ERROR KEY MUST BE WITH UNIQUE NUMBERS!");
- System.exit(0);
- }
- }
- }
- private static String addIntervalsIfNeeded(String message) {
- if(message.length()%8!=0) {
- StringBuilder temp = new StringBuilder(message);
- int numIntervals = message.length()%8;
- temp.append(" ".repeat(Math.max(0, numIntervals)));
- message = temp.toString();
- }
- return message;
- }
- public static int getMin(){
- int min = Integer.MAX_VALUE;
- for(int i=0; i<key.length(); i++){
- if(key.charAt(i) - '0' < min){
- min = key.charAt(i) - '0';
- }
- }
- return min;
- }
- public static int getMax(){
- int min = Integer.MIN_VALUE;
- for(int i=0; i<key.length(); i++){
- if(key.charAt(i) - '0' > max){
- max = key.charAt(i) - '0';
- }
- }
- return max;
- }
- public static int getIndex(char ch){
- for(int i=0; i<key.length(); i++){
- if(key.charAt(i)-48==ch){
- return i;
- }
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement