密钥生成器被初始化为1024,那么为什么打印出的大小是635和162?
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
public class TEST {
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(1024);
return keyPairGenerator.generateKeyPair();
}
public static void main(String[] args) throws Exception {
KeyPair keyPair = generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
System.out.println("Size = " + privateKey.getEncoded().length);
System.out.println("Size = " + publicKey.getEncoded().length);
}
}
sun.security.util.KeyUtil
有一个getKeySize
函数,它接受一个密钥,并根据创建它的算法使用不同的函数返回适当的数字。对于OP的“RSA”密钥对,它使用getModulus().bitLength()
。(我知道sun.security
包不是为程序员而设计的,但是您可以查看最新版本的JDK的源代码作为示例。) - Ti Strgajava.security.Key
的javadoc——它们(两者)都包括AlgorithmIdentifier,指定RSA的OID以及您引用的PKCS1结构,分别包装在BIT STRING和OCTET STRING中。这会增加更多开销。 - dave_thompson_085