我创建了一个聊天应用程序并完成它我必须实现一些加密算法来保护服务器 - 客户端之间的消息。
我的实施是:
1.Client创建kaypair(公钥和私钥)并将公钥发送给服务器
2.Server获取公钥并创建使用公钥加密的对称密钥
3.Server将加密密钥发送给客户端
4.Client用私钥解锁对称密钥。
5.Client和Server与对称密钥通信。
这部分代码是服务器获取公钥并发送加密的对称密钥
的部分 else if(msg.type.equals("pubKey")){
pubKey = msg.content; //get public key
String key = Arrays.toString(crypt.geteKey());
clients[findClient(ID)].send(new Message("symmKey", "SERVER", key, msg.sender));//! //send symmetric key encrypted with public key
}
密钥加密方法:
public void keyEncryption() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
eKey = cipher.doFinal(key.getBlowfishKeyBytes()); //symmetric key encrypted with public key
//System.out.println("2. cipherText= " + bytesToHex(symmKey));
}
我如何从服务器获取加密的对称密钥:
else if(msg.type.equals("symmKey")){
symmKey = (String) msg.content; //get encrypted symmetric key (must unlock with private key)
}
服务器消息类:(客户端消息类具有“对象内容”而不是字符串)
package com.socket;
import java.io.Serializable;
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
public String type, sender,content, recipient;
public Message(String type, String sender, String content, String recipient){
this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
}
@Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
}
}
我将密钥发送到服务器的客户端GUI:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//KeyPair
try {
keyPair = new Keypair();
} catch (NoSuchAlgorithmException ex) {
jTextArea1.append("Security Error! You are not safe!");
}
Object pubKey = keyPair.getKeyPair().getPublic();
username = jTextField3.getText();
password = jPasswordField1.getText();
if (!username.isEmpty() && !password.isEmpty()) {
client.send(new Message("login", username, password, "SERVER"));
client.send(new Message("pubKey",username, pubKey, "SERVER")); //send Public key to Server
}
}
我上服务器出错:
Database exception : userExists()
53846 ERROR reading: cannot assign instance of sun.security.rsa.RSAPublicKeyImpl to field com.socket.Message.content of type java.lang.String in instance of com.socket.Message
我已经实施了第1-3步,但我得到了这个例外......如果有人知道如何处理这个问题,请帮助我。
(如果需要,我会提供任何其他代码。)
谢谢。
答案 0 :(得分:0)
msg.content是String的实例,您尝试将其分配给sun.security.rsa.RSAPublicKeyImpl:
pubKey = msg.content;
答案 1 :(得分:0)
请注意,您的实施看起来容易受到中间人攻击。如果我们打电话给你的客户端和服务器Alice和Bob。我是马洛里 - 一个恶意窃听者。
您需要在协议中引入签名,以帮助确保协议的真实性:Alice和Bob需要确定通信是原始的并且没有被篡改。我在手机上,但看看我能否在以后找到一个不错的链接。