我已经实现了使用字符串在客户端和服务器之间进行通信的 Web 服务。我遇到的问题是将加密字节数组转换为字符串,因为我无法将其转换回服务器端的原始内容。
KeyPairGenerator keyGen;
keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
String publicKeyPath = new String("publicKeys.txt");
publickey = key.getPublic()
byte[] pubEncoded = key.getPublic().getEncoded();
FileOutputStream fout = new FileOutputStream(publicKeyPath);
fout.write(pubEncoded);
fout.flush();
fout.close();
String privateKeyPath = new String("privateKeys.txt");
byte[] privEncoded = key.getPrivate().getEncoded();
fout = new FileOutputStream(privateKeyPath);
fout.write(privEncoded);
fout.flush();
fout.close();
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
并在客户端的每个方法上:
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publickey);
byte[] cipherText = cipher.doFinal(str.getBytes());
port.callX(chiperText.toString());
在服务器端:
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] newPlainText = cipher.doFinal(arg.getBytes());
这给出了“数据必须以零开头”的填充问题
只生成了一个 KeyPair,为了调试,我尝试对同一个函数进行加密和解密,问题取决于从 byte[] 到 String 的转换。
我真的不想将参数的传递更改为其他类型,因为操作是自动生成的,并且所有代码都是字符串。我尝试过使用不同的“UTF-8”和“UTF-16Le”,但都没有:S
任何想法?