我正在尝试使用java.security为Java中的RSA加密获取私钥和公钥。无论我在Google的哪个地方,我都会收到同样的错误消息,说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());
}
}
这是我的秘密课程,实现RSA的密钥派生。这是我的主要
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());
}