我正在使用RSA算法来加密/解密客户端和服务器之间的消息,但在我能做到这一点之前,我需要交换他们的公钥,因为我希望他们每个人拥有自己的对,在我加密后的交换相反的publick键并发送消息。我的问题在于我交换钥匙。这是我的交流部分:
服务器:
ObjectOutputStream obOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream obIn = new ObjectInputStream(socket.getInputStream());
obOut.writeObject(publicKey);
obOut.flush();
Object obj = obIn.readObject();
otherPublicKey = (PublicKey) obj;
客户端:
ObjectOutputStream obOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream obIn = new ObjectInputStream(socket.getInputStream());
obOut.writeObject(publicKey);
obOut.flush();
Object obj = obIn.readObject();
otherPublicKey = (PublicKey) obj;
例外:
javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:325)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:272)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:2086)
我明白我的错误可能是当我将对象转换为PublicKey时。所以我的问题是什么是更合适的方法。
修改
忘记提及我使用此RSA算法进行加密/解密:
public static String encryptWithPublicKey(byte[] message, PublicKey publicKey) throws Exception {
PublicKey apiPublicKey = publicKey;
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsaCipher.init(Cipher.ENCRYPT_MODE, apiPublicKey);
byte[] encVal = rsaCipher.doFinal(message);
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decryptWithPrivateKey(byte[] message, PrivateKey privateKey) throws Exception {
PrivateKey pKey = privateKey;
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsaCipher.init(Cipher.DECRYPT_MODE, pKey);
byte[] decVal = rsaCipher.doFinal(message);
String decryptedValue = new String(decVal);
return decryptedValue;
}
答案 0 :(得分:1)
如果这是所有相关代码,则您需要进行base64编码,但您不能进行base64解码。
答案 1 :(得分:-1)
我会改变它,所以看起来这看起来是否有帮助
客户端:
ObjectOutputStream obOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream obIn = new ObjectInputStream(socket.getInputStream());
obOut.writeObject(publicKey);
obOut.flush();
Object obj = obIn.readObject();
otherPublicKey = (PublicKey) obj;
服务器:
ObjectOutputStream obOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream obIn = new ObjectInputStream(socket.getInputStream());
Object obj = obIn.readObject();
otherPublicKey = (PublicKey)obj;
obOut.writeObject(publicKey);
obOut.flush();