在Android中獲取公鑰的方法有以下幾種:
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
Certificate cert = keyStore.getCertificate(alias);
PublicKey publicKey = cert.getPublicKey();
String publicKeyStr = "-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3r3A8C1M8tY7f0zYVjFy\n" +
"lQIDAQAB\n" +
"-----END PUBLIC KEY-----";
byte[] publicKeyBytes = Base64.decode(publicKeyStr, Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(spec);
URL url = new URL("http://example.com/publicKey.pem");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
byte[] publicKeyBytes = new byte[inputStream.available()];
inputStream.read(publicKeyBytes);
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(spec);
這些方法可以根據具體的情況選擇合適的方式來獲取公鑰。