2010-05-27 117 views
10

密钥生成器初始化的大小为1024,那么为什么打印的大小是635和162?试图了解Java RSA密钥大小

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); 

    } 

} 

回答

20

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 
} 
+0

那么,如何在示例代码中检查其大小? – 2010-05-27 15:36:19

+0

看我的编辑...... – 2010-05-27 16:17:50

4

首先暗示:1024 bits = 128 bytes

二提示:privateKey.getEncoded()返回encoded表示(即,不是原始的)。

+1

感谢提示2,所以我怎么生? – 2010-05-27 15:35:41

+2

“密钥大小”对于不同的编码人员意味着不同的事情,并且不是与密钥相关联。在RSA的情况下,它是模量的大小。 (你应该使用getModulus())看ZZ编码器的答案。 – leonbloy 2010-05-27 15:41:17

+0

出现问题,getModulus返回309位数字。如果这意味着尺寸是309,它仍然不是已经设置的(1024)。 – 2010-05-27 15:44:39