Advertisement
Anton0093

Lab_4 (Sem_2)

Mar 26th, 2021
559
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.92 KB | None | 0 0
  1. import java.math.BigInteger;
  2. import java.util.*;
  3.  
  4. public class RSA {
  5.     //в - 17
  6.  
  7.     private static final int p = 173;
  8.     private static final int q = 313;
  9.  
  10.     private static final BigInteger n = new BigInteger(String.valueOf(p * q));
  11.  
  12.     public static Map<Character, String> alphabitToNumber = new HashMap<>(); //мапа -  ключи: буквы алфавита, значение: число
  13.     public static Map<String, Character> numberToAlphabit = new HashMap<>(); //мапа -  ключи: число, значение: буквы алфавита
  14.  
  15.     public static List<String> listIntegers = new ArrayList<>(); // в этом листе будет строка преобразованная из букв алфавита в числа
  16.     public static List<BigInteger> listNumberLessN = new ArrayList<>(); // лист чисел < n
  17.     public static List<BigInteger> listDecode = new ArrayList<>(); // лист зашифрованных чисел
  18.     public static List<BigInteger> listEncode = new ArrayList<>(); // лист расшифрованных чисел
  19.  
  20.  
  21.     public static int evclidAlg(int a, int b) {
  22.         while (b != 0) {
  23.             int tmp = a % b;
  24.             a = b;
  25.             b = tmp;
  26.         }
  27.         return a;
  28.     }
  29.  
  30.  
  31.     public static String strToIntegerArray(String string){
  32.  
  33.         alphabitToNumber.put('А', "10");
  34.         alphabitToNumber.put('Б', "11");
  35.         alphabitToNumber.put('В', "12");
  36.         alphabitToNumber.put('Г', "13");
  37.         alphabitToNumber.put('Д', "14");
  38.         alphabitToNumber.put('Е', "15");
  39.         alphabitToNumber.put('Ж', "16");
  40.         alphabitToNumber.put('З', "17");
  41.         alphabitToNumber.put('И', "18");
  42.         alphabitToNumber.put('Й', "19");
  43.         alphabitToNumber.put('К', "20");
  44.         alphabitToNumber.put('Л', "21");
  45.         alphabitToNumber.put('М', "22");
  46.         alphabitToNumber.put('Н', "23");
  47.         alphabitToNumber.put('О', "24");
  48.         alphabitToNumber.put('П', "25");
  49.         alphabitToNumber.put('Р', "26");
  50.         alphabitToNumber.put('С', "27");
  51.         alphabitToNumber.put('Т', "28");
  52.         alphabitToNumber.put('У', "29");
  53.         alphabitToNumber.put('Ф', "30");
  54.         alphabitToNumber.put('Х', "31");
  55.         alphabitToNumber.put('Ц', "32");
  56.         alphabitToNumber.put('Ч', "33");
  57.         alphabitToNumber.put('Ш', "34");
  58.         alphabitToNumber.put('Щ', "35");
  59.         alphabitToNumber.put('Ъ', "36");
  60.         alphabitToNumber.put('Ы', "37");
  61.         alphabitToNumber.put('Ь', "38");
  62.         alphabitToNumber.put('Э', "39");
  63.         alphabitToNumber.put('Ю', "40");
  64.         alphabitToNumber.put('Я', "41");
  65.         alphabitToNumber.put(' ', "99");
  66.  
  67.         char[] chars = string.toCharArray();
  68.         for (char aChar : chars) {
  69.             for (Character key : alphabitToNumber.keySet()) {
  70.                 if (aChar == key) { // сравниваем с ключами если равны кидаем в лист
  71.                     listIntegers.add(alphabitToNumber.get(key));
  72.                 }
  73.             }
  74.         }
  75.  
  76.         String[] strings = listIntegers.toArray(new String[0]);
  77.         StringBuilder stringBuilder = new StringBuilder();
  78.         for (String value : strings
  79.              ) {
  80.             stringBuilder.append(value); // соединяем все в одну строку
  81.         }
  82.  
  83.         return stringBuilder.toString();
  84.     }
  85.  
  86.     public static List<BigInteger> Decode(String string, int e){
  87.         char[] chars = string.toCharArray();
  88.         int count = 0;
  89.         for (int i = 0; i < chars.length; i++) {
  90.             if (count < (p * q)) { // сравниваем число с n (p * q)  если меньше n прибавляем следущее
  91.                 count = (count * 10) + (chars[i] - '0');
  92.                 if (i == string.length() - 1) {
  93.                     if (count % 10 == 0){
  94.                         listNumberLessN.add(BigInteger.valueOf(count/10));
  95.                     }
  96.                     else
  97.                         listNumberLessN.add(BigInteger.valueOf(count)); // кидаем в лист
  98.                 }
  99.             }
  100.  
  101.             else{ //если больше, равно n кидаем в лист
  102.                 listNumberLessN.add(BigInteger.valueOf(count / 10));
  103.                 count = ((chars[i-1]-'0') * 10) + (chars[i] -'0');
  104.  
  105. //                if (count == 0){
  106. //                    listNumberLessN.add(BigInteger.valueOf(count));
  107. //                }
  108.                 if (i == string.length() - 1) {
  109.                     if (count % 10 == 0){
  110.                         listNumberLessN.add(BigInteger.valueOf(count/10));
  111.                     }
  112.                     else
  113.                         listNumberLessN.add(BigInteger.valueOf(count)); // кидаем в лист
  114.                 }
  115.             }
  116.         }
  117.         // кодируем наш лист и записываем в новый
  118.         for (BigInteger integer: listNumberLessN
  119.         ) {
  120.             listDecode.add(integer.pow(e).mod(n));
  121.         }
  122.         System.out.println(listDecode);
  123.         return listDecode;
  124.     }
  125.  
  126.     public static String Encode(List<BigInteger> decode, int e){
  127.         numberToAlphabit.put("10", 'А');
  128.         numberToAlphabit.put("11", 'Б');
  129.         numberToAlphabit.put("12", 'В');
  130.         numberToAlphabit.put("13", 'Г');
  131.         numberToAlphabit.put("14", 'Д');
  132.         numberToAlphabit.put("15", 'Е');
  133.         numberToAlphabit.put("16", 'Ж');
  134.         numberToAlphabit.put("17", 'З');
  135.         numberToAlphabit.put("18", 'И');
  136.         numberToAlphabit.put("19", 'Й');
  137.         numberToAlphabit.put("20", 'К');
  138.         numberToAlphabit.put("21", 'Л');
  139.         numberToAlphabit.put("22", 'М');
  140.         numberToAlphabit.put("23", 'Н');
  141.         numberToAlphabit.put("24", 'О');
  142.         numberToAlphabit.put("25", 'П');
  143.         numberToAlphabit.put("26", 'Р');
  144.         numberToAlphabit.put("27", 'С');
  145.         numberToAlphabit.put("28", 'Т');
  146.         numberToAlphabit.put("29", 'У');
  147.         numberToAlphabit.put("30", 'Ф');
  148.         numberToAlphabit.put("31", 'Х');
  149.         numberToAlphabit.put("32", 'Ц');
  150.         numberToAlphabit.put("33", 'Ч');
  151.         numberToAlphabit.put("34", 'Ш');
  152.         numberToAlphabit.put("35", 'Щ');
  153.         numberToAlphabit.put("36", 'Ъ');
  154.         numberToAlphabit.put("37", 'Ы');
  155.         numberToAlphabit.put("38", 'Ь');
  156.         numberToAlphabit.put("39", 'Э');
  157.         numberToAlphabit.put("40", 'Ю');
  158.         numberToAlphabit.put("41", 'Я');
  159.         numberToAlphabit.put("99", ' ');
  160.  
  161.         // декодируем лист
  162.         for (BigInteger integer: decode
  163.              ) {
  164.             listEncode.add(integer.pow(e).mod(n));
  165.         }
  166.         System.out.println(listEncode);
  167.  
  168.         // все эти операции для того чтобы привести лист к строчке))
  169.         BigInteger[] itemsArray = new BigInteger[listEncode.size()];
  170.         itemsArray = listEncode.toArray(itemsArray);
  171.  
  172.         StringBuilder stringBuilder = new StringBuilder();
  173.         for (BigInteger value : itemsArray
  174.         ) {
  175.             stringBuilder.append(value);
  176.         }
  177.  
  178.         String[] strings2Number = CutStringIntoBlocksEncode(stringBuilder.toString());
  179.         StringBuilder stringBuilderDecode = new StringBuilder();
  180.  
  181.         for (String aStr : strings2Number) {
  182.             for (String key : numberToAlphabit.keySet()) {
  183.                 if (aStr.equals(key)) {
  184.                     stringBuilderDecode.append(numberToAlphabit.get(aStr));
  185.                 }
  186.             }
  187.         }
  188.         return stringBuilderDecode.toString();
  189.     }
  190.  
  191.     private static String[] CutStringIntoBlocksEncode(String input) {
  192.  
  193.         String[] Blocks = new String[(input.length())/2];
  194.         int lengthOfBlock = input.length() / Blocks.length;
  195.  
  196.         for (int i = 0; i < Blocks.length; i++) {
  197.  
  198.             Blocks[i] = input.substring(i * lengthOfBlock, lengthOfBlock * (i + 1));
  199.  
  200.         }
  201.         return Blocks;
  202.     }
  203.  
  204.     public static void printBigIntegerList(List<BigInteger> DecodeList){
  205.         BigInteger[] itemsArray = new BigInteger[DecodeList.size()];
  206.         itemsArray = DecodeList.toArray(itemsArray);
  207.  
  208.         for (BigInteger bigInt: itemsArray
  209.         ) {
  210.             System.out.print(bigInt);
  211.         }
  212.         System.out.println("\n");
  213.     }
  214.  
  215.     private static int getE(int pq){
  216.         int e;
  217.         for (e = 2; e < pq; e++) {
  218.  
  219.             if (evclidAlg(e, pq) == 1) {
  220.                 break;
  221.             }
  222.         }
  223.         return e;
  224.     }
  225.  
  226.     private static int getD(int e, int pq){
  227.         int d = 0;
  228.         for (int i = 0; i <= 9; i++) {
  229.             int x = 1 + (i * pq);
  230.  
  231.             if (x % e == 0) {
  232.                 d = x / e;
  233.                 break;
  234.             }
  235.         }
  236.         return d;
  237.     }
  238.  
  239.     public static void main(String[] args) {
  240.  
  241.         int e = getE((p-1) * (q-1)); // получили e
  242.         int d = getD(e,(p-1) * (q-1)); // получили d
  243.  
  244.         System.out.println("e: "+ e);
  245.         System.out.println("d: "+ d);
  246.         System.out.println("n: "+ n);
  247.  
  248.         String string = "ДОБРЫЙ ВЕЧЕР АНТОН";
  249.         // удаляем все последовательности букв, длиньше двух (таких в русском языке нет)
  250.         string = string.replaceAll("([А-Я])\\1{2,}", "$1$1");
  251.         System.out.println("String: " + string);
  252.  
  253.         String strToIntegerArray = strToIntegerArray(string);
  254.         System.out.println("String in numbers: " + strToIntegerArray);
  255.         System.out.println("\n");
  256.  
  257.         System.out.println("Decode: ");
  258.         List<BigInteger> DecodeList = Decode(strToIntegerArray, e);
  259.         printBigIntegerList(DecodeList);
  260.  
  261.         System.out.println("Encode: ");
  262.         String EncodeStr = Encode(DecodeList, d);
  263.         System.out.println(EncodeStr);
  264.     }
  265. }
  266.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement