Частотная атака, символы отображаются некорректно при попытке их распечатать (верхнее нижнее, нижнее верхнее) - PullRequest
1 голос
/ 06 мая 2020

Я работаю над частотной атакой, чтобы получить ключ шифрования текста. Я написал один, однако полученный ключ почти идентичен используемому, однако верхние символы теперь ниже, а нижние символы - вверху. Более того, числа даже не отображаются. Я действительно не знаю, как исправить эту проблему.

Это выставленный код:

    public static char[] encryptionKey = new char[4];
    public static String letters = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static char[] stringToCharArray(String str){
        char[] res = new char[str.length()];
        for (int i = 0; i < str.length(); i++){
            res[i] = str.charAt(i);
        }
        return res;
    }

    public static void G(){
        for (int i = 0; i < 4; i++){
            Random random = new Random();
            encryptionKey[i] = letters.charAt(random.nextInt(letters.length()));
        }
    }

    public static String E(String clearText){
        char[] clearTextChars = stringToCharArray(clearText);
        char[] encryptedTextChars = new char[clearTextChars.length];
        for (int i = 0; i < clearTextChars.length; i++){
            encryptedTextChars[i] = (char) (clearTextChars[i] ^ encryptionKey[i % 4]);
        }
        return new String(encryptedTextChars);
    }

    public static String D(String encryptedText){
        char[] encryptedTextChars = stringToCharArray(encryptedText);
        char[] clearTextChars = new char[encryptedTextChars.length];
        for (int i = 0; i < encryptedTextChars.length; i++){
            clearTextChars[i] = (char) (encryptedTextChars[i] ^ encryptionKey[i % 4]);
        }
        return new String(clearTextChars);
    }

    public static char maxOccuringChar(String text){
        int[] counter = new int[256];
        for (int i = 0; i < text.length(); i++){
            counter[text.charAt(i)]++;
        }
        int max = -1;
        char res = ' ';
        for (int i = 0; i < text.length(); i++){
            if (max < counter[text.charAt(i)]){
                max = counter[text.charAt(i)];
                res = text.charAt(i);
            }
        }
        return res;
    }

    public static String[] splitString(String str){
        String[] parts = new String[4];
        parts[0] = "";
        parts[1] = "";
        parts[2] = "";
        parts[3] = "";
        char[] strChars = stringToCharArray(str);
        for (int i = 0; i < strChars.length; i++){
            parts[i%4] += strChars[i];
        }
        return parts;
    }

    public static char[] maxOccOnParts(String[] parts){
        char[] possibleKey = new char[4];
        possibleKey[0] = maxOccuringChar(parts[0]);
        System.out.println("p1 ->"+(int) possibleKey[0]);
        possibleKey[1] = maxOccuringChar(parts[1]);
        System.out.println("p2 ->"+(int) possibleKey[1]);
        possibleKey[2] = maxOccuringChar(parts[2]);
        System.out.println("p3 ->"+(int) possibleKey[2]);
        possibleKey[3] = maxOccuringChar(parts[3]);
        System.out.println("p4 ->"+(int) possibleKey[3]);

        return possibleKey;
    }

    public static void printEncryptionKey(){
        System.out.println("Encryption key : "+ new String(encryptionKey));
    }

    public static void main(String[] args) {
        G();
        printEncryptionKey();
        String test = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
        // System.out.println("Length = "+test.length());
        // System.out.println("Split = "+test.length()/4);
        String testEncrypted = E(test);
        String testDecrypted = D(testEncrypted);
        System.out.println("String : " + test);
        System.out.println("Encrypted : " + testEncrypted);
        System.out.println("Decrypted : " + testDecrypted);
        String[] strArray = splitString(testEncrypted);
        for (String str : strArray) {
          System.out.println(str);
        }
        System.out.println("MaxOccuringChar per split part");
        char[] key = maxOccOnParts(strArray);
        for (char ch : key){
            System.out.println(ch);
        }
    }

Это один из результатов, которые может создать этот код:

Encryption key : 3Gad
String : Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Encrypted : (^g(@2
                  DZ4AZJg^*DG"(DG/DC5
G.&3V4G..F4JiA(\5       F*A
                           R4AV"DG/DZ)@34AG&R5DW2
                                                        JgK3AE"D@.Vg
                                                                    VgPQwH0     ]g
2](
]33
V>AXgDT&
^"DQ(g(/4E.Wg   Q+.DG(A R,DRgC"AC"
             Gg
_>AZ1DP"F@kAF3A_4DG/D_".\V$\3V4G.g^&
Z)DV4]_+DF)
           R)WiA-Gg@g
A.Wg                 C2
R4D\!A(V3@"D@/G4A\)Z)"
Tg-
   A"
G/AV4Dz7^g@4V4MDR)D^(5VJg
@/AF%
Tg
  U3A"Z,Dr+@g1T",X"DZF#
TgA4
   ]4A
      Ug-
         A"
#7^>AV?D\!A["AA.Z)DR)DG>@"Z)DZ)@3g-
                                   A"
]#G5C@gR)A#AF*                       Dz7^g      @gV)A["A
              3GgV5AZ)3 vTT4MDD/
&DF)

\0DC5
Jg3Vg&AR+
WgA&
    _"DZ3A\g
            X"A3VgV$    V)A\(
E"AV)A.gG@(A["V&DZ)
P3                 "
] A@4G>@"Z)H5   R.
G/A["AV+@"A(07F+Z4.DG/D~WT@g
           Ug-G5V3A["@g
].                     ]3
[g@,A-C4        7@&@kA]#A       \5DA"]3
X"A%_#V[.4G0Vg
W.1@.
@g
  V*A-C4
Decrypted : Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
^@ZZJ^GGCGVGFJ\FRVGZ@GRWJKE@VV]]]XTVUC]PQGRRCC^QEWG_ZPF@F_G_\V\VG^ZV]_FRWG@CAWZGAR\V@@G\ZTAz^@VR^VJGV\F@TUAZr@TXZFTA]UAz^\F@^^V\[AZRG@ZZ@Az^@V[]G@RAFGVZDF\CGGRJVWA_Z\XVVV\[@ZJEVAG@[VZP]G@ZR]@G_]]FZG@G[V@UGV[@]]VC@@]\A][@CQ[GVX_VV]W@@VC
(g24*g*"(/5.&34..4i5*4"/)34&52g3".ggw0g2(733g&>g"#5+.(,g"""(g/4.gg>1"5k34/".g$)34.g&)43+))igg2.g3v43/"4!3"/4))g"7g44)(5)g/47%/g3",+g"")#g44g"7i5*g7#>?!".))>"))3g"7gg)"#5g)#*3g5)3v4/&)05"(&+g3gg&"3g"3g$)(&21)(g").gg("&)"3.>")5. 4.>$ g07+4./~g/"+"g53"g3.
                                              *47&k#5"30g,g+.40g"#
5$.1.g
      *4
(
 AAAA
A-AAAAAA
  MA
AA-
AAA-A
        AAA
           A    TM
A
A
 A
AAA     (WAAA-AAAA
DDD
(
  DDD   D
         QH


D
DD      D

DDD
DD
  -

RDDD(D

DDD

DD



DDDDD
CTD  D
D
D
D
D JDD

 DH
DDT

-       D
%
-
MaxOccuringChar per split part
Encryption key found:
p1 ->19
p2 ->103
p3 ->65
p4 ->68

g
A
D

Мы видим, что символы "инвертированы" по сравнению с исходным ключом шифрования вверху, и что число не отображается, но я распечатал значение int этих символов, чтобы посмотреть, смогу ли я что-нибудь найти ... Я не знал.

Честно говоря, я не знаю, когда возникает эта проблема, и как ее исправить. Ожидаемый результат - это ключ шифрования, используемый здесь в начале вывода. Думаю, моя атака работает, потому что это те же буквы.

Что бы порекомендовали исправить эту проблему, пожалуйста?

Спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...