试图了解Java 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; 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); } } 

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 } 

第一个提示: 1024 bits = 128 bytes

第二个提示: privateKey.getEncoded()返回一个encoded表示(即不是raw)。