gpt4 book ai didi

java - 仿射密码解密过程错误结果

转载 作者:行者123 更新时间:2023-12-01 13:02:11 25 4
gpt4 key购买 nike

我在解密短信时遇到问题。示例:

明文:“光环兄弟”

密文:“Å⁄iÌ=ßOÌÅbO”

明文:“haフo`bメothナメ”

k1 : 33 ->第一个键

k2 : 125 ->第二个 key

我使用 ASCII 可打印和 ASCII 扩展字符集总共 224 个字符。

这是我的代码:

public class Affine {

//encyption method
public static String enkripsi(String pesan, int k1, int k2){

//change text message into array
char[] chars = pesan.toCharArray();

//getting ASCII code from each characters index
int[] ascii = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ascii[i] = (int) chars[i];
}

//Affine encryption formula
int[] c = new int[ascii.length];
for (int j = 0; j < ascii.length; j++) {
c[j] = ((k1*ascii[j])+k2) % 224 ;
}

//change the decimal (ASCII code) value back to characters
char[] charen = new char[c.length];
for (int i = 0; i < c.length; i++) {
charen[i] = (char)c[i];
}

//change characters to String
String pesan_en = String.valueOf(charen);
return pesan_en;
}

//decryption method
public static String dekripsi(String isipesanMasuk, int k1, int k2){
int j,g;
int[] c;
int[] f = new int [224];

//change text message into array
char[] chars = isipesanMasuk.toCharArray();

//getting ASCII code from each characters index
int[] ascii = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ascii[i] = (int) chars[i];
}


//getting inverse from encryption formula of Affine
//example 33f = 1 (mod) 224 -> f = (1+(224 * j)) / 5
//g = (33 * f) mod 224
//if g = 1 then stop
for (j = 1; j < 224; j++) {
f[j] = (1 +(224*j)) / k1;
g = (k1*f[j]) % 224 ;
if (g==1) {
break;
}
}

//Affine decrypion formula
c = new int[ascii.length];
for (int k = 0; k < ascii.length; k++) {
c[k] = (f[j]*(ascii[k]-k2)) % 224 ;
}

//change the decimal (ASCII code) value back to characters
char[] charde = new char[c.length];
for (int i = 0; i < c.length; i++) {
charde[i] = (char)c[i];
}

//change characters to String
String pesan_de = String.valueOf(charde);
return pesan_de;
}
}

最佳答案

如果 ascii[k]-k2 给出负值,解密公式就会失效。要解决这个问题,请使用以下命令:

c[k] = (f[j]*(ascii[k]-k2+224)) % 224;

其他一些备注:

您不需要数组来计算 k1 的倒数,一个简单的整数变量即可。

加密可能会导致控制字符(\u0000 到\u000f 和\u007f 到\u009f)可能无法在所有 channel 中原样传输。

关于java - 仿射密码解密过程错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23440879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com