解密短信时遇到问题。示例:
明文:“晕兄弟”
密文:“žiÌ=ßOÌÅbO”
明文:“haフo`bメothナメ”k1:33 - >第一个键
k2:125 - >第二个键
我使用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;
}
}
答案 0 :(得分:1)
如果ascii[k]-k2
给出负值,则解密公式会失效。要解决这个问题,请使用:
c[k] = (f[j]*(ascii[k]-k2+224)) % 224;
其他一些评论:
你不需要一个数组来计算k1
的倒数,一个简单的整数变量就可以了。
加密可能导致控制字符(\ u0000到\ u000f和\ u007f到\ u009f)可能无法在所有通道中不加改变地传输。