0

我正在开发使用 Web 服务的 Java 应用程序,然后验证用户,我让用户输入他的用户名和密码。要使用此应用程序,用户需要有效的用户名和密码。

我有一个上下文菜单,当登录正确时会被激活。否则我希望它被禁用。

我只想要一次验证。因此,如果任何其他用户从同一系统使用该应用程序,他不需要再次输入密码。

这意味着我需要将密码保存在本地系统中,以便在整个应用程序中使用此密码

无论如何保存密码有什么帮助吗?

4

1 回答 1

0

好吧,您可以使用公钥和私钥来加密或解密密码。

编辑:

首先,您必须创建一个公钥/私钥对。为此,您需要工具 openssl(http://www.openssl.org/source/或直接用于 Windows http://www.openssl.org/related/binaries.html)。安装它,打开“cmd”(如果您在 Windows 上),导航到您的 openssl 安装路径并输入以下行以生成服务器和客户端的密钥:

openssl genrsa -out serverPrivateKey.pem 2048
openssl rsa -in serverPrivateKey.pem -pubout -outform DER -out serverPublicKey.der

openssl genrsa -out clientPrivateKey.pem 2048
openssl pkcs8 -topk8 -nocrypt -in clientPrivateKey.pem -outform der -out clientPrivateKey.der
openssl rsa -in clientPrivateKey.pem -pubout -outform PEM -out clientPublicKey.pem

现在,在您的 Web 服务 Java 应用程序中,您可以导入公钥进行加密

File pubKeyFile = new File("keys/serverPublicKey.der");
byte[] buffer = new byte[(int) pubKeyFile.length()];

DataInputStream in = new DataInputStream(new FileInputStream(pubKeyFile));
in.readFully(buffer);
in.close();

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(buffer));

并加密您的密码:

String text = password;

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = cipher.doFinal(text.getBytes());

并将其保存到本地文件系统:

FileOutputStream fos = new FileOutputStream("/tmp/encrypted");
fos.write(encrypted);
fos.flush();
fos.close();

另一种解密方式。

导入私钥:

File privKeyFile = new File("keys/clientPrivateKey.der");
byte[] buffer = new byte[(int) privKeyFile.length()];

DataInputStream in = new DataInputStream(new FileInputStream(privKeyFile));
in.readFully(buffer);
in.close();

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(buffer));

读取加密文件:

File cryptedData = new File("/tmp/encrypted");
buffer = new byte[(int) cryptedData.length()];

in = new DataInputStream(new FileInputStream(cryptedData));
in.readFully(buffer);
in.close();

并解密:

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.DECRYPT_MODE, privateKey);

byte[] decrypted = cipher.doFinal(buffer);

String data = new String(decrypted);

System.out.println(data);

您只需在运行 Web 服务的系统上保密您的私钥。您可以提供一个 Web 服务功能,该功能将公钥提供给客户端进行加密。您的客户端只需将加密的文本字符串发送到 Web 服务,该服务对其进行解密并验证您的客户端。

于 2013-04-19T07:04:56.670 回答