我对加密的txt没有很好的解密时间。
public class Practica2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a text: ");
String txt = input.nextLine();
System.out.println("Enter a num of columns: ");
int num = input.nextInt();
String cipher = cipherTrans(txt, num);
System.out.println("Coded: " + cipher);
String decipher = decipherTrans(cipher, num);
System.out.println("Decoded: " + decipher);
}
//This method encrypts
private static String cipherTrans(String txt, int num) {
String output = "";
//takes the length of the string and divides by the num of columns
int num2 = (int) Math.ceil(txt.length()*1.0/num);
//2d array
char[][] buffer = new char[num2][num];
int k = 0;
//loop which will store and rearrange the letter of the txt
for (int i = 0; i < num2; i++) {
for (int j = 0; j < num; j++, k++) {
if (txt.length() > k) {
buffer[i][j] = txt.charAt(k);
}
}
}
//loop which will store the rearrenged txt and output the encrypted txt
for (int j = 0; j < num; j++) {
for (int i = 0; i < num2; i++) {
output += buffer[i][j];
}
}
return output;
}
//this method will decrypt the encrypted txt
private static String decipherTrans(String txt, int num) {
String output = "";
int num2 = (int) Math.ceil(txt.length() * 1.0 / num);
char[][] buffer = new char[num2][num];
int k = 0;
for (int i = 0; i < num2; i++) {
for (int j = 0; j < num; j++, k++) {
if (txt.length() > k) {
buffer[i][j] = txt.charAt(k);
}
}
}
for (int i = 0; i < num; i++){
for (int j = 0; j < num2; j++){
txt += buffer[j][i];
}
}
return output;
}
}电流输出:
输入一个文本:我的名字是dani,输入一个列的数字:5编码: mm : mdim n ayaseni
预期输出:
输入一个文本:我的名字是dani,输入一个列的数字:5编码: mm排列的aninasi解码:我的名字是dani
发布于 2021-10-07 17:53:06
转位表
这是您的密文:mm yed aninasi;密钥长度是5。
您的特定案例的换位表如下所示:
char[][] buffer = {
{'m', 'y', ' ', 'n', 'a'},
{'m', 'e', ' ', 'i', 's'},
{' ', 'd', 'a', 'n', 'i'}
};如何生成转位表?
“.收件人必须通过将消息密文长度除以密钥长度来计算列长度,然后他们可以再次将消息写入列中,.”
出发地:
如何破译信息?
一旦生成了转位表,只需从左到右逐行读取它。
解决方案
基于代码的工作解密方法可能如下所示:
private static String decipherTrans(String txt, int num) {
int num2 = (int) Math.ceil(txt.length() * 1.0 / num);
char[][] buffer = new char[num2][num];
int k = 0;
for (int i = 0; i < num; i++) {
for (int j = 0; j < num2; j++, k++) {
if (txt.length() > k) {
buffer[j][i] = txt.charAt(k);
}
}
}
String output = "";
for (int i = 0; i < num2; i++){
for (int j = 0; j < num; j++){
output += buffer[i][j];
}
}
return output;
}您只需要清楚地知道要正确使用数组索引所做的事情。
https://stackoverflow.com/questions/69472486
复制相似问题