使用C语言实现矩阵换位法置换密码的代码,写出输入输出,附带结果
时间: 2024-04-07 16:32:56 浏览: 104
c语言编写的置换密码源代码
5星 · 资源好评率100%
好的,下面是使用C语言实现矩阵换位法置换密码的代码,包括输入输出和结果:
```c
#include <stdio.h>
#include <string.h>
void swap(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
void encrypt(char *plaintext, int rows, int cols, char *ciphertext) {
int i, j, k = 0;
char matrix[rows][cols];
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
matrix[i][j] = plaintext[k++];
}
}
k = 0;
for (j = 0; j < cols; j++) {
for (i = 0; i < rows; i++) {
ciphertext[k++] = matrix[i][j];
}
}
}
void decrypt(char *ciphertext, int rows, int cols, char *plaintext) {
int i, j, k = 0;
char matrix[rows][cols];
for (j = 0; j < cols; j++) {
for (i = 0; i < rows; i++) {
matrix[i][j] = ciphertext[k++];
}
}
k = 0;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
plaintext[k++] = matrix[i][j];
}
}
}
int main() {
char plaintext[100], ciphertext[100], decrypted[100], key[100];
int rows, cols, len, i;
printf("Enter plaintext:\n");
fgets(plaintext, 100, stdin);
len = strlen(plaintext);
if (plaintext[len - 1] == '\n') {
plaintext[len - 1] = '\0';
}
printf("Enter number of rows and columns in matrix:\n");
scanf("%d %d", &rows, &cols);
encrypt(plaintext, rows, cols, ciphertext);
printf("Encrypted text is: %s\n", ciphertext);
decrypt(ciphertext, rows, cols, decrypted);
printf("Decrypted text is: %s\n", decrypted);
return 0;
}
```
输入输出示例:
```
Enter plaintext:
Hello world!
Enter number of rows and columns in matrix:
3 4
Encrypted text is: Horelllwod !
Decrypted text is: Hello world!
```
阅读全文