gpt4 book ai didi

java - KeyPairGenerator 不适用于 RSA 的 java

转载 作者:行者123 更新时间:2023-12-01 18:04:39 26 4
gpt4 key购买 nike

我正在尝试使用java.security获取java中RSA加密的私钥和公钥。无论我在哪里谷歌,我总是收到同样的错误,说NoSuchAlgorithException。


class secret {
void secret(){
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
PublicKey pubkey = kp.getPublic();
PrivateKey privkey = kp.getPrivate();
System.out.println(privkey.getEncoded()+"---"+pubkey.getEncoded());
}
}

这是我的 secret 类,它实现 RSA 的 key 派生。这是我的主要

class project {
public static void main(String[] args) {
System.out.println("Hello!");
secret sec = new secret();
}
}

这是错误

javac project.java
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true
project.java:11: error: unreported exception NoSuchAlgorithmException; must be caught or declared to be thrown
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
^
1 error

最佳答案

方法 KeyPairGenerator#getInstance 定义为

public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException

NoSuchAlgorithmException 是 checked exception 。你必须处理它:

static void secret(){
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
PublicKey pubkey = kp.getPublic();
PrivateKey privkey = kp.getPrivate();
System.out.println(privkey.getEncoded()+"---"+pubkey.getEncoded());
}

关于java - KeyPairGenerator 不适用于 RSA 的 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com