实现简单的加密和解密Java函数
发布时间:2023-11-18 22:03:13
要实现简单的加密和解密函数,可以使用替换法或移位法等基本的加密算法。以下是一个实现简单替换法加密和解密的Java函数:
1. 加密函数:
public static String encrypt(String input, int shift) {
StringBuilder encrypted = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isLetter(ch)) {
if (Character.isUpperCase(ch)) {
char encryptedCh = (char) ((ch - 'A' + shift) % 26 + 'A');
encrypted.append(encryptedCh);
} else {
char encryptedCh = (char) ((ch - 'a' + shift) % 26 + 'a');
encrypted.append(encryptedCh);
}
} else {
encrypted.append(ch);
}
}
return encrypted.toString();
}
该函数接受两个参数:输入字符串和移位数。它遍历输入字符串的每个字符,如果是字母,则根据是否是大写或小写字母进行加密,加密过程是将字符的ASCII码减去相应字母的ASCII码并加上移位数,然后取模26(因为英文字母只有26个),最后再加上相应字母的ASCII码得到加密后的字母。如果不是字母,则直接追加到加密结果中。最终返回加密结果。
2. 解密函数:
public static String decrypt(String input, int shift) {
StringBuilder decrypted = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isLetter(ch)) {
if (Character.isUpperCase(ch)) {
char decryptedCh = (char) ((ch - 'A' - shift + 26) % 26 + 'A');
decrypted.append(decryptedCh);
} else {
char decryptedCh = (char) ((ch - 'a' - shift + 26) % 26 + 'a');
decrypted.append(decryptedCh);
}
} else {
decrypted.append(ch);
}
}
return decrypted.toString();
}
该函数同样接受两个参数:输入字符串和移位数。解密过程与加密过程相反,即将加密后的字母的ASCII码减去移位数,并加上相应字母的ASCII码,最后取模26得到解密后的字母。最终返回解密结果。
使用例子:
public static void main(String[] args) {
String message = "Hello, World!";
int shift = 3;
String encryptedMessage = encrypt(message, shift);
System.out.println("Encrypted message: " + encryptedMessage);
String decryptedMessage = decrypt(encryptedMessage, shift);
System.out.println("Decrypted message: " + decryptedMessage);
}
输出结果:
Encrypted message: Khoor, Zruog! Decrypted message: Hello, World!
这个例子中,将字符串"Hello, World!"使用移位数3进行加密,然后再使用相同的移位数进行解密,最终得到原始字符串。注意,该函数只能加密和解密纯字母字符串,对于非字母字符不进行处理。也可以根据需要修改加密算法或解密算法来实现其他简单的加密和解密方法。
