Java 无法从规范中检索RSA私钥,
通过使用下面的程序,我生成了公钥和私钥,并将它们转换为规范。从规范中可以很好地检索到公钥,但不能完全从规范中检索到私钥。我在下面的程序中有什么错误吗Java 无法从规范中检索RSA私钥,,java,Java,通过使用下面的程序,我生成了公钥和私钥,并将它们转换为规范。从规范中可以很好地检索到公钥,但不能完全从规范中检索到私钥。我在下面的程序中有什么错误吗 import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.RSAPublicKeySpec; i
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
public class KeyFactoryEx {
public static void main(String args[]) throws NoSuchAlgorithmException, InvalidKeySpecException{
KeyFactory factory = KeyFactory.getInstance("RSA");
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
KeyPair pair = keyGen.genKeyPair();
PublicKey pubKey = pair.getPublic();
PrivateKey priKey = pair.getPrivate();
byte pubKeyEncoded[] = pubKey.getEncoded();
byte priKeyEncoded[] = priKey.getEncoded();
System.out.println("Public key is");
for(byte b : pubKeyEncoded)
System.out.print(b +" ");
System.out.println();
System.out.println("Private key is");
for(byte b : priKeyEncoded)
System.out.print(b +" ");
System.out.println();
KeySpec pubKeySpec = factory.getKeySpec(pubKey, RSAPublicKeySpec.class);
KeySpec priKeySpec = factory.getKeySpec(priKey, RSAPrivateKeySpec.class);
System.out.println("Key Specifications are generated for public and private keys");
System.out.println("Retrieving public key from pubKeySpec");
PublicKey pubSpecKey = factory.generatePublic(pubKeySpec);
pubKeyEncoded = pubSpecKey.getEncoded();
for(byte b : pubKeyEncoded)
System.out.print(b +" ");
System.out.println();
System.out.println("Retrieving Private key from priKeySpec");
PrivateKey priSpecKey = factory.generatePrivate(priKeySpec);
priKeyEncoded = priSpecKey.getEncoded();
for(byte b : priKeyEncoded)
System.out.print(b +" ");
System.out.println();
}
}
它实际上是同一个键,只是一个不同的表示。如果您尝试打印第一个PrivateKey的类,您会注意到它是RSAPrivateCrtKeyImpl。第二个具有RSAPrivateKeyImpl类型 您可以将第一个PrivateKey强制转换为RSAPrivateCrtKey,并检索CRT值以及专用指数和模数。但是,底部的PrivateKey不是RSAPrivateCrtKey,而是RSAPrivateKey,因此它没有CRT值 您可以在调用getKeySpec时使用RSAPrivateCrtKeySpec而不是使用RSAPrivateKeySpec来纠正这一问题