createSSLContext e : java.security.InvalidAlgorithmParameterException: parameter must be ECParameterSpec or ECGenParameterSpec
时间: 2023-10-15 16:56:21 浏览: 209
这个错误是由于在初始化`KeyPairGenerator`时,使用了错误的参数类型导致的。为了解决这个问题,你需要使用`ECGenParameterSpec`来指定椭圆曲线的名称。
以下是修改后的代码示例:
```java
try {
String certPath = "/proc/gsboard/dev_info/security/certificate";
byte[] certContent = File2byte(new File(certPath));
String keyPath = "/proc/gsboard/dev_info/security/private_key";
byte[] keyContent = File2byte(new File(keyPath));
byte[] certBytes = parseDERFromPEM(certContent, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] keyBytes = parseDERFromPEM(keyContent, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
X509Certificate cert = generateCertificateFromDER(certBytes);
PrivateKey key = generatePrivateKeyFromDER(keyBytes);
// 限制椭圆曲线
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC", "BC");
parameters.init(new ECGenParameterSpec("secp256r1")); // 或者"secp384r1", "secp521r1"
ECParameterSpec ecSpec = parameters.getParameterSpec(ECParameterSpec.class);
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("EC", "BC");
keyPairGen.initialize(ecSpec);
KeyStore keystore = KeyStore.getInstance("BKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, null, new Certificate[]{cert});
KeyManagerFactory kmf = KeyManagerFactory.getInstance("EC", "BC"); // 使用EC算法
kmf.init(keystore, null);
KeyManager[] km = kmf.getKeyManagers();
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sslContext = SSLContext.getInstance("TLSV1.2");
sslContext.init(km, trustAllCerts, null);
return sslContext;
} catch (Exception e) {
Log.i(TAG, "createSSLContext e : " + e);
return null;
}
```
这样修改后的代码应该能够正确地限制使用指定的椭圆曲线。请注意,你需要根据实际情况进行适当的调整和测试。
阅读全文