※系统环境:
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 - 私钥(需要在档案开头与结尾各加上
# '