我正在尝试使用我从php服务器获取的公钥在Android应用程序中输入一个字符串。
php服务器代码:
$res = openssl_pkey_new();
openssl_pkey_export($res, $privKey);
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
echo $pubKey;
服务器正确创建密钥。在我的应用程序中,我将公钥存储在“response”变量中。这个var就像: response =“----- BEGIN PUBLIC KEY ----- MIIB ...... etc ... wIDAQAB ----- END PUBLIC KEY -----”
Android代码:
String pass = "password";
String strEncryInfoData="";
try {
KeyFactory keyFac = KeyFactory.getInstance("RSA");
KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(response.trim().getBytes(), Base64.DEFAULT));
Key publicKey = keyFac.generatePublic(keySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = cipher.doFinal(pass.getBytes());
strEncryInfoData = new String(Base64.encode(cipherText,Base64.DEFAULT));
} catch (Exception e){
}
运行应用程序时,出现此错误: java.security.spec.InvalidKeySpecException:java.lang.RuntimeException:error:0D0680A8:asn1编码例程:ASN1_CHECK_TLEN:标记错误
我不知道为什么代码没有输入密码。任何的想法?它是关于编码类型的? 感谢。
答案 0 :(得分:0)
尝试删除BEGIN标头和END页脚以及所有换行符,然后获得需要解码并传递给X509EncodedKeySpec
构造函数的Base64编码的DER。这是一些代码:
response = response.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");
response = response.replace("\n", "").replace("\r", "");
// Use Base64.NO_WRAP because: https://stackoverflow.com/questions/32935783/java-different-results-when-decoding-base64-string-with-java-util-base64-vs-and/32935972
byte[] responseBytes = Base64.decode(response, Base64.NO_WRAP);
KeySpec keySpec = new X509EncodedKeySpec(responseBytes);