#include <stdio.h>
#include <string.h>
// 转制式密码加密方法
void transposeEncrypt(char *text, int numCols, char *encrypted) {
int len = strlen(text);
int index = 0;
for (int col = 0; col < numCols; col++) {
for (int i = col; i < len; i += numCols) {
encrypted[index++] = text[i];
}
}
encrypted[len] = '\0';
}
// 转制式密码解密方法
void transposeDecrypt(char *text, int numCols, char *decrypted) {
int len = strlen(text);
int numRows = (len + numCols - 1) / numCols;
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int i = row; i < len; i += numRows) {
decrypted[i] = text[index++];
}
}
decrypted[len] = '\0';
}
int main() {
char text[1000];
int numCols;
printf("请输入明文: ");
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
printf("请输入转制的列数: ");
scanf("%d", &numCols);
getchar(); // 清除换行符
char encrypted[1000];
char decrypted[1000];
transposeEncrypt(text, numCols, encrypted);
transposeDecrypt(encrypted, numCols, decrypted);
printf("加密结果: %s\n", encrypted);
printf("解密结果: %s\n", decrypted);
return 0;
}
转置式密码的加密和解密
于 2025-03-05 09:41:03 首次发布