用java语言分别实现可输入数值的仿射密码和希尔密码,并且能够正常运行
时间: 2024-09-28 16:14:49 浏览: 33
在Java中,我们可以使用`Scanner`类获取用户输入的数值,然后结合数组和位操作来实现仿射密码和希尔密码。这里我将简要地描述一下这两个密码体制的基础实现:
### 1. 仿射密码 (Caesar Cipher)
仿射密码是一种简单的替换加密方法,通常通过固定偏移量对字母表进行循环移位。以下是基础版本的实现:
```java
import java.util.Scanner;
import java.util.Arrays;
public class AffineCipher {
private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入明文:");
String plaintext = scanner.nextLine().toUpperCase();
System.out.println("请输入偏移量(a和b):");
int a = scanner.nextInt();
int b = scanner.nextInt();
// 取模处理,保证偏移量在字母表范围内
a = a % ALPHABET.length();
b = b % ALPHABET.length();
// 仿射变换
char[] ciphertext = encrypt(plaintext.toCharArray(), a, b);
System.out.println("加密后的密文: " + new String(ciphertext));
}
public static char[] encrypt(char[] input, int a, int b) {
for (int i = 0; i < input.length; i++) {
if (input[i] >= 'A' && input[i] <= 'Z') {
input[i] = (char) ((ALPHABET.indexOf(input[i]) + a - 1 + b) % 26 + 'A');
}
}
return input;
}
}
```
### 2. 希尔密码 (Vigenere Cipher)
希尔密码是一种基于替换的复用密码系统,它使用了一个密钥序列来加密文本。这里我们简化成每个字符都用固定长度的密钥进行替换:
```java
import java.util.Scanner;
import java.util.zip.Cipher;
public class HillCipher {
private static final int KEY_SIZE = 2; // 希尔矩阵的大小
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入明文:");
String plaintext = scanner.nextLine().toUpperCase();
System.out.println("请输入密钥(由大写字母组成,至少两字符长):");
String key = scanner.nextLine().toUpperCase();
// 对于不足KEY_SIZE的密钥,填充到足够长度
while (key.length() < KEY_SIZE) {
key += key.charAt(0);
}
// 初始化密钥矩阵
char[][] keyMatrix = new char[KEY_SIZE][KEY_SIZE];
for (int i = 0; i < KEY_SIZE; i++) {
for (int j = 0; j < KEY_SIZE; j++) {
keyMatrix[i][j] = key.charAt(i * key.length() + j);
}
}
// 转换为整数矩阵
int[][] intKeyMatrix = convertCharsToNumbers(keyMatrix);
// 加密
char[] ciphertext = encrypt(plaintext.toCharArray(), intKeyMatrix);
System.out.println("加密后的密文: " + new String(ciphertext));
}
private static int[][] convertCharsToNumbers(char[][] matrix) {
int[][] result = new int[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
result[i][j] = ALPHABET.indexOf(matrix[i][j]);
}
}
return result;
}
public static char[] encrypt(char[] input, int[][] keyMatrix) {
int len = input.length;
char[] ciphertext = new char[len];
for (int i = 0; i < len; i += KEY_SIZE) {
int rowStart = i % KEY_SIZE;
int colStart = i / KEY_SIZE;
for (int j = 0; j < KEY_SIZE; ++j) {
ciphertext[rowStart + j] = (char) ((input[colStart + j] + keyMatrix[j][rowStart]) % 26 + 'A');
}
}
return ciphertext;
}
}
```
**
阅读全文