试图了解Java RSA密钥大小

试图了解Java RSA密钥大小,java,encryption,rsa,Java,Encryption,Rsa,密钥生成器的初始大小为1024,那么为什么打印的大小是635和162呢 import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.interfaces.RSAPrivateKey; impor

密钥生成器的初始大小为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);

    }

}

第一个提示:
1024位=128字节


第二个提示:
privateKey.getEncoded()
返回一个
编码的
表示(即非原始)。RSA密钥由模和指数组成。密钥大小是指模数中的位。因此,即使没有任何编码开销,您也需要超过128字节来存储1024位密钥

getEncoded()返回ASN.1 DER编码对象。私钥甚至包含CRT参数,所以它非常大

要获得关键尺寸,请执行以下操作

System.out.println("Key size = " + publicKey.getModulus().bitLength());
以下是相关ASN.1对象

RSAPrivateKey ::= SEQUENCE {
    version           Version,
    modulus           INTEGER,  -- n
    publicExponent    INTEGER,  -- e
    privateExponent   INTEGER,  -- d
    prime1            INTEGER,  -- p
    prime2            INTEGER,  -- q
    exponent1         INTEGER,  -- d mod (p-1)
    exponent2         INTEGER,  -- d mod (q-1)
    coefficient       INTEGER,  -- (inverse of q) mod p
    otherPrimeInfos   OtherPrimeInfos OPTIONAL
}


RSAPublicKey ::= SEQUENCE {
    modulus           INTEGER,  -- n
    publicExponent    INTEGER   -- e
}

“密钥大小”对于不同的编码者意味着不同的东西,并且与密钥的关系并不简单。对于RSA,它是模的大小。(您应该使用GetModular())请参阅ZZ编码器的答案。有问题,GetModular返回的数字为309位。如果这意味着大小是309,它仍然不是a设置的(1024)。第三个提示:1024*Log10(2)=308.25=>1024位~309位十进制数字对于将来在google上找到它的其他人来说,类
sun.security.util.KeyUtil
有一个
getKeySize
函数,该函数接受一个密钥,并且基于它是用什么算法创建的,使用不同的函数返回相应的数字。对于OP的“RSA”密钥对,它使用
GetModules().bitLength()
。(我知道
sun.security
软件包不是供程序员使用的,而是作为一个例子。)不完全是这样。JCE使用可以处理多个算法的通用编码——X.509/PKIX中的SubjectPublicKeyInfo和PKCS8/rfc5208中的PrivateKeyInfo,请参阅java doc for
java.security.Key
——其中(两者)包括一个算法标识符,指定RSA的OID以及(对于RSA)您引用的PKCS1结构,分别用位字符串和八位字节字符串包装。这会增加(甚至)更多的开销。