利用Java函数实现简单的加密/解密算法
发布时间:2023-07-01 19:43:58
在Java中,可以使用多种方式实现简单的加密/解密算法。下面是其中两种常用的方式。
1. 异或运算加密/解密算法:
异或运算是一种在比特级别上进行的操作,它将两个二进制数的对应位相比较,如果相同则输出0,如果不同则输出1。在加密/解密算法中,我们可以通过将明文与密钥进行异或运算来进行加密,再通过将密文与密钥进行异或运算来进行解密。
public class XORCipher {
public static void main(String[] args) {
String plaintext = "Hello, World!";
String key = "secret";
String ciphertext = encrypt(plaintext, key);
System.out.println("Ciphertext: " + ciphertext);
String decryptedText = decrypt(ciphertext, key);
System.out.println("Decrypted Text: " + decryptedText);
}
public static String encrypt(String plaintext, String key) {
StringBuilder ciphertext = new StringBuilder();
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
char k = key.charAt(i % key.length());
ciphertext.append((char) (c ^ k));
}
return ciphertext.toString();
}
public static String decrypt(String ciphertext, String key) {
return encrypt(ciphertext, key);
}
}
在上面的例子中,我们使用了一个简单的异或运算加密/解密算法。在加密时,我们将明文的每个字符与密钥的对应字符进行异或运算,并将结果添加到密文中。在解密时,我们将密文的每个字符与密钥的对应字符进行异或运算,并将结果添加到明文中。
2. 凯撒密码加密/解密算法:
凯撒密码是一种简单的替换密码,它通过将明文中的每个字母移动固定的位置来进行加密。在加密时,我们可以将明文中的每个字母向后移动固定的位置,而在解密时,我们将密文中的每个字母向前移动同样的位置。
public class CaesarCipher {
public static void main(String[] args) {
String plaintext = "Hello, World!";
int key = 3;
String ciphertext = encrypt(plaintext, key);
System.out.println("Ciphertext: " + ciphertext);
String decryptedText = decrypt(ciphertext, key);
System.out.println("Decrypted Text: " + decryptedText);
}
public static String encrypt(String plaintext, int key) {
StringBuilder ciphertext = new StringBuilder();
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
if (Character.isLetter(c)) {
char shifted = (char) (c + key);
if (Character.isUpperCase(c) && shifted > 'Z') {
ciphertext.append((char) (shifted - 26));
} else if (Character.isLowerCase(c) && shifted > 'z') {
ciphertext.append((char) (shifted - 26));
} else {
ciphertext.append(shifted);
}
} else {
ciphertext.append(c);
}
}
return ciphertext.toString();
}
public static String decrypt(String ciphertext, int key) {
return encrypt(ciphertext, -key);
}
}
在上面的例子中,我们使用了凯撒密码算法。在加密时,我们将明文的每个字母移动固定的位置,即向后移动key个位置,并判断移动后的字母是否超出了字母表的范围。如果超出了范围,则需要将其重新映射到字母表中。在解密时,我们将密文的每个字母向前移动同样的位置,即向前移动key个位置。
