通过使用以下程序生成公钥和私钥,将它们转换为规范。公钥从规范中检索得很好,但私钥不是从规范中完全检索的。我在下面的程序中做错了。
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();
}
}
答案 0 :(得分:1)
它实际上是相同的键,它只是一个不同的表示。如果您尝试打印第一个PrivateKey的类,您会注意到它是RSAPrivateCrtKeyImpl。第二个类型为RSAPrivateKeyImpl。
您可以将第一个PrivateKey转换为RSAPrivateCrtKey,并检索CRT值以及私有指数和模数。但是底部的PrivateKey不是RSAPrivateCrtKey而只是RSAPrivateKey,所以它没有CRT值。
您可以在调用getKeySpec而不是使用RSAPrivateKeySpec时使用RSAPrivateCrtKeySpec来解决此问题。