作者kuangs (kuangs)
看板java
标题[问题] Java OAEP With SHA-256 解码错误
时间Tue Dec 31 14:30:37 2019
※系统环境:
openssl 1.0.2g
Java8
※状况概述:
我设计一个网页来作认证使用,由网页端提供私钥与随机字串,
让使用者用私钥来加密字串後,再传回网页端并使用公钥来解密进行认证。
目前我在网页端(Java)进行加密/解密测试都可以正常运作,但在模拟客户端测试时,
由客户端使用openssl用私钥加密字串传回网页端时,发现网页端解密都会失败。
※程式码:
网页端产生私钥:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded()); //私钥
Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded()); //公钥
网页端(Java):
String PRIVATE_KEY = "MII........vCF4="; //私钥
String PUBLIC_KEY = "MII.......wIDAQAB";//公钥
String STRING = "u8xeve.....x82NA=="; //加密过後字串
String str = "XXXXXX"; //随机字串
byte[] result;
//[测试] 私钥加密
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(PRIVATE_KEY));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
cipher.init(Cipher.ENCRYPT_MODE, privateKey, oaepParameterSpec);
result = cipher.doFinal(Base64.getDecoder().decode(str));
System.out.println("Result : " + Base64.getEncoder().encodeToString(result));
//公钥解密
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(PUBLIC_KEY));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, publicKey, oaepParameterSpec);
result = cipher.doFinal(STRING.getBytes());
System.out.println("Result : " + Base64.getEncoder().encodeToString(result));
客户端(openssl):
# encr.txt - 随机字串
# private.pem - 私钥(需要在档案开头与结尾各加上
# '-----BEGIN PRIVATE KEY-----'与'-----END PRIVATE KEY-----')
openssl pkeyutl -in encr.txt -encrypt -inkey private.pem \
-pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 \
-pkeyopt rsa_mgf1_md:sha256 |openssl base64
※错误讯息:
cipher.doFinal(Base64.getDecoder().decode(str)) <-- unable to decrypt block
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 59.115.97.79 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/java/M.1577773839.A.3FE.html
※ 编辑: kuangs (59.115.97.79 台湾), 12/31/2019 14:48:17
※ 编辑: kuangs (59.115.97.79 台湾), 12/31/2019 14:50:02
1F:→ ssccg: 用私钥加密、用「公钥」解密,那加密的意义在哪? 12/31 16:49
2F:→ ssccg: 如果是认证应该用签章演算法 12/31 16:58
3F:→ reon: 不要乱用啊..私钥只能用来解密和签章~公钥是加密 01/19 01:34
4F:推 gn00273680: 楼上正确 01/25 15:40