我有以下工作流程。在使用openssl生成rsa密钥对
向java服务器发布公钥
服务器在内存中构造公钥
服务器用公钥加密文本并发回blob
Python用私钥解密blob
生成公钥/私钥对:openssl genrsa -out privkey.pem 1024 # generate private key
openssl rsa -in privkey.pem -pubout > pubkey.pem # derive public key
openssl pkcs8 -topk8 -in privkey.pem -outform PEM -inform PEM -nocrypt -out privkey.pkcs8 # convert private key to PKCS8 format
Python代码
^{pr2}$
Java服务器代码:package com.hs.works;
import org.apache.commons.codec.binary.Base64;
import org.eclipse.jetty.http.HttpStatus;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.security.KeyFactory;
import javax.crypto.Cipher;
public class CryptServlet extends HttpServlet {
byte[] encrypt(byte[] pubKey, String text) {
try {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey k = (RSAPublicKey) keyFactory.generatePublic(keySpec);
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String key = req.getParameter("key");
byte[] decoded_bytes = Base64.decodeBase64(key.getBytes());
byte[] encoded = encrypt(decoded_bytes, "SECRET_TEXT");
resp.setStatus(HttpStatus.OK_200);
resp.getWriter().write(new String(Base64.encodeBase64(encoded)));
}
}
输出:>>>f = open('/tmp/decoded.txt', 'rb')
>>>c = f.read()
>>> c
'\x02bt\x1bq\xb1\x9bc\xef\xe30Q,o)
>>>
>>> c[len(c) - 11:]
'SECRET_TEXT'
在python端打印输出时,我在输出中看到了SECRET_文本,但同时也有很多乱七八糟的东西。在
我不确定这是否与填充物或其他问题有关。在