我使用Java从私钥中生成公钥,如下所示,
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
PrivateKey priv = kp.getPrivate();
RSAPrivateCrtKey rsaCrtKey = (RSAPrivateCrtKey) priv;
RSAPublicKeySpec keyspecPublic = new RSAPublicKeySpec(rsaCrtKey.getModulus(), rsaCrtKey.getPublicExponent());
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey publicKey2 = kf.generatePublic(keyspecPublic);
String publicString = Base64.getMimeEncoder().encodeToString(publicKey2.getEncoded());
StringBuilder sb = new StringBuilder("");
sb.append("\"-----BEGIN PUBLIC KEY-----\\n")
.append(publicString)
.append("\\n-----END PUBLIC KEY-----");
然后我使用openssl
为相同的私钥生成公钥,
openssl rsa -in private.key -pubout -out public.key
但是以上两种方法生成不同长度的字符串作为公共密钥。我在这里做错什么了吗?
java代码中的公钥:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6UkqbaGp7wOx2vrtqxmX/22ixKZcZPfZ
xXAawIst+AsWyNS+99MxnilstLIBKd6BCzJJsAa2I0ks43mnNZbkx1f1um+tQpXuTMbTh5MRprPn
jmX6aF+JXJbXATKhabTIQcCdpnrMi6scp9nWYkFdxVMfvo1gyThzfPwPgCO4eRFo1IkwZuergkl7
e0+U7WonqzFEb0joy5P78U+K8HebDW7nbS8zliq3DH2FI9yvEK3LeEN+Sa5icMWlERGv+7FCJVIH
CjBYfzaRZD9qqld/AnAEkCVt38SfSqWJECsnJYUW90WuFd8IxUVPS0TMfFMQhJFMT3eGweBOUb/b
pDm/hQIDAQAB
-----END PUBLIC KEY-----
来自openssl
的公钥:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6UkqbaGp7wOx2vrtqxmX
/22ixKZcZPfZxXAawIst+AsWyNS+99MxnilstLIBKd6BCzJJsAa2I0ks43mnNZbk
x1f1um+tQpXuTMbTh5MRprPnjmX6aF+JXJbXATKhabTIQcCdpnrMi6scp9nWYkFd
xVMfvo1gyThzfPwPgCO4eRFo1IkwZuergkl7e0+U7WonqzFEb0joy5P78U+K8Heb
DW7nbS8zliq3DH2FI9yvEK3LeEN+Sa5icMWlERGv+7FCJVIHCjBYfzaRZD9qqld/
AnAEkCVt38SfSqWJECsnJYUW90WuFd8IxUVPS0TMfFMQhJFMT3eGweBOUb/bpDm/
hQIDAQAB
-----END PUBLIC KEY-----
答案 0 :(得分:3)
密钥是相同的,并且将解码为相同的字节内容。
从格式上讲,Java封装在76列中,而OpenSSL封装在64列中。
如果要使换行一致,请使用Base64.getMimeEncoder(int lineLength, byte[] lineSeparator)
重载方法,该方法可指定行长并将64
作为lineLength
参数传递。
Base64.getMimeEncoder(64, new byte[] {'\r', '\n'});