x.509 Cert - 如何生成商店文件?

时间:2016-04-22 05:30:57

标签: java

好的,我正在使用下面的代码来自学x.509证书。我的问题是,我是否应该在其他地方生成证书或商店文件,然后将文件附加到项目中?或者项目是否应该在程序中生成所有这些?我的错误是它无法找到商店文件。

1 个答案:

答案 0 :(得分:1)

基本上,这两个程序希望已经创建了证书和密钥库,名称为user.storecrypt.cer,并且这两个文件位于程序所在的文件夹中。

要生成这些文件,您可以使用java发行版中的keytool创建密钥库和证书,然后从中导出公共证书。

以下是服务器的步骤:

int port = 7999;
ServerSocket server = new ServerSocket(port);
Socket s = server.accept();
ObjectInputStream is = new ObjectInputStream(s.getInputStream());

服务器在端口7999上打开一个侦听套接字,并期待一些内容。

//Read the keystore and retrieve the server's private key  
//Default keystore is jks
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream("user.store"), password);
PrivateKey dServer = (PrivateKey)ks.getKey(aliasname, password);

它获取一个位于名为user.store的文件中的密钥库(相对文件到您推送程序的位置。从该密钥库中,它获取别名为aliasname的私钥("user"在你的情况下)。

//Decrypt: server's private key 
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
byte[] in = (byte[]) is.readObject();
cipher.init(Cipher.DECRYPT_MODE, dServer);
byte[] plaintText = cipher.doFinal(in);
System.out.println("The plaintext is: " + new String(plaintText));
server.close();

使用私钥解密发送到套接字的内容并将其打印在标准输出(通常是控制台)

现在为客户:

String host = "localhost";
int port = 7999;
Socket s = new Socket(host, port);

ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());

它连接到端口7999

上的套接字
 //Client loads server's cert
InputStream inStream = new FileInputStream("crypt.cer");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);

从文件crypt.cer获取服务器的公共证书(再次相对) 然后,它会检查证书的有效性。

//Get public key from cert
RSAPublicKey eServer = (RSAPublicKey) cert.getPublicKey();

//Encrypt with RSA as key generation algorithm 
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, eServer);
byte[] cipherText = cipher.doFinal(message.getBytes());
System.out.println("Ciphertext: " + cipherText);
os.writeObject(cipherText);
os.flush();
os.close();
s.close();
input.close();

这会加密消息(用户输入的消息)并将其发送到服务器。

相关问题