尝试了解 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);
}
}
The key generator was initilized with a size of 1024, so why the printed sizes are 635 and 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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个提示:
1024 位 = 128 字节
第二个提示:
privateKey.getEncoded()
返回一个编码
表示形式(即不是原始的)。First hint:
1024 bits = 128 bytes
Second hint:
privateKey.getEncoded()
returns anencoded
representation (i.e. not raw).RSA 密钥由模数和指数组成。密钥大小是指模数中的位数。因此,即使没有任何编码开销,您也需要超过 128 个字节来存储 1024 位密钥。
getEncoded() 返回 ASN.1 DER 编码对象。私钥甚至包含 CRT 参数,因此它非常大。
要获取密钥大小,请执行以下操作,
以下是相关的 ASN.1 对象,
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.
getEncoded() returns ASN.1 DER encoded objects. The private key even contains CRT parameters so it's very large.
To get key size, do something like this,
Here are the relevant ASN.1 objects,