当命令keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 执行时没有错误,这是一个输出示例。
Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10,000 days for: CN=a, OU=a, O=a, L=a, ST=a, C=a
Enter key password for <mykey>
(RETURN if same as keystore password):
[Storing my-release-key.jks]
但是是什么导致了java.security.NoSuchAlgorithmException: RSA KeyGenerator not available?
此错误表示 keytool 尝试通过 RSA 无效算法实例化 KeyGenerator 对象。为什么 RSA 是 KeyGenerator 的无效算法?这是因为 RSA 是一种非对称密钥的算法,而 KeyGenerator 是一个创建对称密钥的类。
现在让我们做一些测试来澄清想法并使用 RSA 创建一个 KeyGenerator 对象:
public class KeyGeneratorTest {
public static void main(String[] args) {
try {
KeyGenerator keyGeneratorTest=KeyGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
前面的代码产生了问题中报告的相同异常:
java.security.NoSuchAlgorithmException: RSA KeyGenerator not available
at javax.crypto.KeyGenerator.<init>(KeyGenerator.java:169)
at javax.crypto.KeyGenerator.getInstance(KeyGenerator.java:223)
现在我将尝试使用 keytool 和 RSA 算法参数创建一个对称密钥。
keytool -genseckey -alias mytest2 -keyalg RSA -keysize 192 -storetype JCEKS
输出与问题报告的完全相同。
keytool error: java.security.NoSuchAlgorithmException: RSA KeyGenerator not available
抛出错误是因为内部keytool -genseckey 命令尝试使用 RSA 算法参数 (-keyalg RSA) 创建 KeyGenerator 对象,并且我提到 RSA 不是用于创建对称密钥的有效算法。
请访问以下文档以了解有关 keytool 的更多信息。
List of Java Standard Algorithm Names、NoSuchAlgorithmException Documentation、Keytool source code 和 Keytool reference documentation