试图了解 Java RSA 密钥大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2921508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to understand Java RSA key size
提问by Tom Brito
The key generator was initilized with a size of 1024, so why the printed sizes are 635 and 162?
密钥生成器的初始化大小为 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);
}
}
回答by ZZ Coder
RSA keys are made of Modulus and Exponent. The key size refers to the bits in modulus. So even without any encoding overhead, you will need more than 128 bytes to store 1024-bit keys.
RSA 密钥由模数和指数组成。密钥大小是指模数中的位。因此,即使没有任何编码开销,您也需要超过 128 个字节来存储 1024 位密钥。
getEncoded() returns ASN.1 DER encoded objects. The private key even contains CRT parameters so it's very large.
getEncoded() 返回 ASN.1 DER 编码对象。私钥甚至包含 CRT 参数,因此非常大。
To get key size, do something like this,
要获得密钥大小,请执行以下操作,
System.out.println("Key size = " + publicKey.getModulus().bitLength());
Here are the relevant ASN.1 objects,
这是相关的 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
}
回答by leonbloy
First hint: 1024 bits = 128 bytes
第一个提示: 1024 bits = 128 bytes
Second hint: privateKey.getEncoded()returns an encodedrepresentation (i.e. not raw).
第二个提示:privateKey.getEncoded()返回一个encoded表示(即不是原始的)。

