Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.BigInteger;
- import java.util.*;
- public class RSA {
- //в - 17
- private static final int p = 173;
- private static final int q = 313;
- private static final BigInteger n = new BigInteger(String.valueOf(p * q));
- public static Map<Character, String> alphabitToNumber = new HashMap<>(); //мапа - ключи: буквы алфавита, значение: число
- public static Map<String, Character> numberToAlphabit = new HashMap<>(); //мапа - ключи: число, значение: буквы алфавита
- public static List<String> listIntegers = new ArrayList<>(); // в этом листе будет строка преобразованная из букв алфавита в числа
- public static List<BigInteger> listNumberLessN = new ArrayList<>(); // лист чисел < n
- public static List<BigInteger> listDecode = new ArrayList<>(); // лист зашифрованных чисел
- public static List<BigInteger> listEncode = new ArrayList<>(); // лист расшифрованных чисел
- public static int evclidAlg(int a, int b) {
- while (b != 0) {
- int tmp = a % b;
- a = b;
- b = tmp;
- }
- return a;
- }
- public static String strToIntegerArray(String string){
- alphabitToNumber.put('А', "10");
- alphabitToNumber.put('Б', "11");
- alphabitToNumber.put('В', "12");
- alphabitToNumber.put('Г', "13");
- alphabitToNumber.put('Д', "14");
- alphabitToNumber.put('Е', "15");
- alphabitToNumber.put('Ж', "16");
- alphabitToNumber.put('З', "17");
- alphabitToNumber.put('И', "18");
- alphabitToNumber.put('Й', "19");
- alphabitToNumber.put('К', "20");
- alphabitToNumber.put('Л', "21");
- alphabitToNumber.put('М', "22");
- alphabitToNumber.put('Н', "23");
- alphabitToNumber.put('О', "24");
- alphabitToNumber.put('П', "25");
- alphabitToNumber.put('Р', "26");
- alphabitToNumber.put('С', "27");
- alphabitToNumber.put('Т', "28");
- alphabitToNumber.put('У', "29");
- alphabitToNumber.put('Ф', "30");
- alphabitToNumber.put('Х', "31");
- alphabitToNumber.put('Ц', "32");
- alphabitToNumber.put('Ч', "33");
- alphabitToNumber.put('Ш', "34");
- alphabitToNumber.put('Щ', "35");
- alphabitToNumber.put('Ъ', "36");
- alphabitToNumber.put('Ы', "37");
- alphabitToNumber.put('Ь', "38");
- alphabitToNumber.put('Э', "39");
- alphabitToNumber.put('Ю', "40");
- alphabitToNumber.put('Я', "41");
- alphabitToNumber.put(' ', "99");
- char[] chars = string.toCharArray();
- for (char aChar : chars) {
- for (Character key : alphabitToNumber.keySet()) {
- if (aChar == key) { // сравниваем с ключами если равны кидаем в лист
- listIntegers.add(alphabitToNumber.get(key));
- }
- }
- }
- String[] strings = listIntegers.toArray(new String[0]);
- StringBuilder stringBuilder = new StringBuilder();
- for (String value : strings
- ) {
- stringBuilder.append(value); // соединяем все в одну строку
- }
- return stringBuilder.toString();
- }
- public static List<BigInteger> Decode(String string, int e){
- char[] chars = string.toCharArray();
- int count = 0;
- for (int i = 0; i < chars.length; i++) {
- if (count < (p * q)) { // сравниваем число с n (p * q) если меньше n прибавляем следущее
- count = (count * 10) + (chars[i] - '0');
- if (i == string.length() - 1) {
- if (count % 10 == 0){
- listNumberLessN.add(BigInteger.valueOf(count/10));
- }
- else
- listNumberLessN.add(BigInteger.valueOf(count)); // кидаем в лист
- }
- }
- else{ //если больше, равно n кидаем в лист
- listNumberLessN.add(BigInteger.valueOf(count / 10));
- count = ((chars[i-1]-'0') * 10) + (chars[i] -'0');
- // if (count == 0){
- // listNumberLessN.add(BigInteger.valueOf(count));
- // }
- if (i == string.length() - 1) {
- if (count % 10 == 0){
- listNumberLessN.add(BigInteger.valueOf(count/10));
- }
- else
- listNumberLessN.add(BigInteger.valueOf(count)); // кидаем в лист
- }
- }
- }
- // кодируем наш лист и записываем в новый
- for (BigInteger integer: listNumberLessN
- ) {
- listDecode.add(integer.pow(e).mod(n));
- }
- System.out.println(listDecode);
- return listDecode;
- }
- public static String Encode(List<BigInteger> decode, int e){
- numberToAlphabit.put("10", 'А');
- numberToAlphabit.put("11", 'Б');
- numberToAlphabit.put("12", 'В');
- numberToAlphabit.put("13", 'Г');
- numberToAlphabit.put("14", 'Д');
- numberToAlphabit.put("15", 'Е');
- numberToAlphabit.put("16", 'Ж');
- numberToAlphabit.put("17", 'З');
- numberToAlphabit.put("18", 'И');
- numberToAlphabit.put("19", 'Й');
- numberToAlphabit.put("20", 'К');
- numberToAlphabit.put("21", 'Л');
- numberToAlphabit.put("22", 'М');
- numberToAlphabit.put("23", 'Н');
- numberToAlphabit.put("24", 'О');
- numberToAlphabit.put("25", 'П');
- numberToAlphabit.put("26", 'Р');
- numberToAlphabit.put("27", 'С');
- numberToAlphabit.put("28", 'Т');
- numberToAlphabit.put("29", 'У');
- numberToAlphabit.put("30", 'Ф');
- numberToAlphabit.put("31", 'Х');
- numberToAlphabit.put("32", 'Ц');
- numberToAlphabit.put("33", 'Ч');
- numberToAlphabit.put("34", 'Ш');
- numberToAlphabit.put("35", 'Щ');
- numberToAlphabit.put("36", 'Ъ');
- numberToAlphabit.put("37", 'Ы');
- numberToAlphabit.put("38", 'Ь');
- numberToAlphabit.put("39", 'Э');
- numberToAlphabit.put("40", 'Ю');
- numberToAlphabit.put("41", 'Я');
- numberToAlphabit.put("99", ' ');
- // декодируем лист
- for (BigInteger integer: decode
- ) {
- listEncode.add(integer.pow(e).mod(n));
- }
- System.out.println(listEncode);
- // все эти операции для того чтобы привести лист к строчке))
- BigInteger[] itemsArray = new BigInteger[listEncode.size()];
- itemsArray = listEncode.toArray(itemsArray);
- StringBuilder stringBuilder = new StringBuilder();
- for (BigInteger value : itemsArray
- ) {
- stringBuilder.append(value);
- }
- String[] strings2Number = CutStringIntoBlocksEncode(stringBuilder.toString());
- StringBuilder stringBuilderDecode = new StringBuilder();
- for (String aStr : strings2Number) {
- for (String key : numberToAlphabit.keySet()) {
- if (aStr.equals(key)) {
- stringBuilderDecode.append(numberToAlphabit.get(aStr));
- }
- }
- }
- return stringBuilderDecode.toString();
- }
- private static String[] CutStringIntoBlocksEncode(String input) {
- String[] Blocks = new String[(input.length())/2];
- int lengthOfBlock = input.length() / Blocks.length;
- for (int i = 0; i < Blocks.length; i++) {
- Blocks[i] = input.substring(i * lengthOfBlock, lengthOfBlock * (i + 1));
- }
- return Blocks;
- }
- public static void printBigIntegerList(List<BigInteger> DecodeList){
- BigInteger[] itemsArray = new BigInteger[DecodeList.size()];
- itemsArray = DecodeList.toArray(itemsArray);
- for (BigInteger bigInt: itemsArray
- ) {
- System.out.print(bigInt);
- }
- System.out.println("\n");
- }
- private static int getE(int pq){
- int e;
- for (e = 2; e < pq; e++) {
- if (evclidAlg(e, pq) == 1) {
- break;
- }
- }
- return e;
- }
- private static int getD(int e, int pq){
- int d = 0;
- for (int i = 0; i <= 9; i++) {
- int x = 1 + (i * pq);
- if (x % e == 0) {
- d = x / e;
- break;
- }
- }
- return d;
- }
- public static void main(String[] args) {
- int e = getE((p-1) * (q-1)); // получили e
- int d = getD(e,(p-1) * (q-1)); // получили d
- System.out.println("e: "+ e);
- System.out.println("d: "+ d);
- System.out.println("n: "+ n);
- String string = "ДОБРЫЙ ВЕЧЕР АНТОН";
- // удаляем все последовательности букв, длиньше двух (таких в русском языке нет)
- string = string.replaceAll("([А-Я])\\1{2,}", "$1$1");
- System.out.println("String: " + string);
- String strToIntegerArray = strToIntegerArray(string);
- System.out.println("String in numbers: " + strToIntegerArray);
- System.out.println("\n");
- System.out.println("Decode: ");
- List<BigInteger> DecodeList = Decode(strToIntegerArray, e);
- printBigIntegerList(DecodeList);
- System.out.println("Encode: ");
- String EncodeStr = Encode(DecodeList, d);
- System.out.println(EncodeStr);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement