2010-05-27 71 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