我有一种应生成RSA公钥的方法:
import android.util.Base64;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
...
private PublicKey generatePublicKey() throws IOException {
try {
String encodedPublicKey = "TUl...QUI="; // real content is hidden
byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
return keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException e) {
String msg = "Invalid key specification: " + e;
throw new IOException(msg);
}
}
但是在try-block中执行最后一条语句时会抛出异常:
InvalidKeySpecException:java.lang.RuntimeException: 错误:0c0000be:ASN.1编码例程:OPENSSL_internal:WRONG_TAG
这是怎么了?
您可以尝试使用以下encodedPublicKey
进行调试:
TUlJQkNnS0NBUUVBNjFCam1mWEdFdldtZWduQkdTdVMrclU5c29VZzJGbk9EdmEzMkQxQXFod2R6aXdISU5GYQpEMU1WbGNyWUc2WFJLZmtjeG5hWEdmRkRXSExFdk5CU0VWQ2dKanRIQUdaSW01R0wvS0E4NktEcC9Dd0RGTVN3Cmx1b3djWHdEd295aW5tZU9ZOWVLeWg2YVk3MnhKaDdub0xCQnExTjBiV2kxZTJpKzgzdHhPQ2c0eVYyb1ZYaEIKbzhwWUVKOExUM2VsNlNteG9sM0Mxb0ZNVmR3UGdjMHZUbDI1WHVjTWNHL0FMRS9LTlk2cHFDMkFRNlIyRVJsVgpnUGlVV09QYXRWa3Q3K0JzM2g1UmFteGg3WGpCT1hldWxtQ3BHU3luWE5jcFovMDYrdm9mR2kvMk1scFFaTmhICkFvOGVheU1wNkZjdk51Y0lwVW5kbzFYOGRLTXYzWTI2WlFJREFRQUI =