2014-10-28 3463 views
3

如果我這樣做:爲什麼我的RSA 2048公鑰的長度是294字節?

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); 
kpg.initialize(2048); 
KeyPair kp = kpg.genKeyPair(); 
Key publicKey = kp.getPublic(); 
byte [] pubKey = publicKey.getEncoded(); 
System.out.println("Size: " + pubKey.length); 

我的產值是294不應該RSA 2048的輸出是256個字節長?

回答

5

RSA密鑰不包含隨機字節,例如AES密鑰;它由數字組成。 RSA的密鑰大小由模數定義,但它也需要一個公開指數(通常是第四個費馬或另一個小素數)。因此,getEncoded()都被返回嵌入到ASN.1 DER編碼的字節數組中,該字節數組通常出現在名爲SubjectPublicKeyInfo的X5.09證書中。

如果要提取密鑰大小,請改爲使用((RSAPublicKey) publicKey).getModulus().bitLength()。要查看結構,請使用openssl asn1parse或使用在線解碼器,如this

2
publicKey.getEncoded(); 

這將以標準格式返回一個帶有一些開銷(如算法標識符)的編碼密鑰。

如果你真的想原始密鑰材料,你可以轉換爲RSAPublicKey和呼叫getModulus()getPublicExponent()(給你BigInteger S)。

相關問題