import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class EncryptDecrypt {
/**
* 加密
*/
public static String Encrypt(String pass) {
int len = pass.length();
char enPass[] = new char[len * 2];
int chk[] = { 104, 115, 109, 97, 122, 104, 106, 104 };
if (pass == null || pass.equals(“”))
return “”;
int i = 0;
for (int j = 0; i < len; j++) {
if (j == 8) {
j = 0;
}
int temp = pass.charAt(i) ^ chk[j];
String C = Integer.toString(temp, 16);
if (C.length() > 1) {
enPass[i * 2] = C.charAt(0);
enPass[i * 2 + 1] = C.charAt(1);
} else {
enPass[i * 2] = ‘0’;
enPass[i * 2 + 1] = C.charAt(0);
}
i++;
}
return new String(enPass);
}
/**
* 解密
*/
public static String unEncrypt(String enPass) {
int len = enPass.length();
if (len % 2 != 0) {
return "";
}
if (enPass == null || enPass.equals(""))
return "";
char pass[] = new char[len / 2];
char C[] = new char[2];
int chk[] = { 104, 115, 109, 97, 122, 104, 106, 104 };
int i = 0;
for (int j = 0; i < len / 2; j++) {
if (j == 8) {
j = 0;
}
C[0] = enPass.charAt(i * 2);
C[1] = enPass.charAt(i * 2 + 1);
int temp = Integer.parseInt(String.valueOf(C), 16);
pass[i] = (char) (temp ^ chk[j]);
i++;
}
return new String(pass);
}

public static void main(String args[]) {
//unicode在线编码《请输入数据库密码(回车确认): \u8BF7\u8F93\u5165\u6570\u636E\u5E93\u5BC6\u7801(\u56DE\u8F66\u786E\u8BA4):》
System.out.println("\u8BF7\u8F93\u5165\u6570\u636E\u5E93\u5BC6\u7801(\u56DE\u8F66\u786E\u8BA4):");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String pwd = br.readLine();
System.out.println("================\u56DE\u8F66\u79BB\u5F00");
System.out.println("\u539F\u5BC6\u7801\uFF1A" + pwd);
System.out.println("\u52A0\u5BC6\u5BC6\u7801\uFF1A" + Encrypt(pwd));
System.out.println("\u52A0\u5BC6\u5BC6\u7801\uFF1A" + unEncrypt(Encrypt(pwd)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果如下:


该博客展示了如何使用Java实现简单的字符串加密和解密功能。代码中定义了两个方法,`Encrypt`用于加密,`unEncrypt`用于解密,它们使用了一个固定的密钥数组进行异或操作。在主方法中,程序接收用户输入,然后加密和解密显示结果。这个例子对于理解基本的字符串加密原理有一定帮助。
1203

被折叠的 条评论
为什么被折叠?



