gpt4 book ai didi

java - 在 Java 中从 PEM 字符串创建 DSA 公钥

转载 作者:行者123 更新时间:2023-11-30 05:43:56 25 4
gpt4 key购买 nike

已使用创建 DSA key 对

ssh-keygen -t dsa

然后使用将公钥部分转换为pem格式

openssl dsa -in mytestkey -pubout

然后我尝试使用以下内容构建公钥:

            private static final String PUBLIC_KEY_PEM =
"-----BEGIN PUBLIC KEY-----\n" +
"MIIBtzCCASsGByqGSM44BAEwggEeAoGBAJLJRIrDdiwbB6iWZTWowprJB8QfbLK7\n" +
"8OUCoj6Ot5nfEL5VDPcc0v1rCGQxmL+nijPQsxA0LTucBySlkj6AvGIdND6yY7Qx\n" +
"OZYeP6UErByzVhmDNG2MIhK7SL36O3uutOJKr86aTiDxP8/zSUO8JPZHqtr2K2Cm\n" +
"lY6LQpocGnZ/AhUAmA/eq9AcGaNAqbT6ebB3IE3qWKkCgYAuh3zCz9aTPJ8+D9to\n" +
"6xjjE6SEqKM4EDaA8kpV/363ad8kZRLRmtxTGDpIKV/k4ebb94+4o6VEFJKTUH7t\n" +
"7c5uj8Hnr+8scctFE85nXprpK/CmxvWIZRl0AWjz1/8hoaUX3ZcLz9QbOLk1deSS\n" +
"BksFgKZQgoaNVY3PPq0pjNfdCAOBhQACgYEAkDATEoqoCXMOy/LK+TOBqXWu3Tex\n" +
"kkBMTJxYHyhXqmBLvvkiwBX1wz0i58Zg0Qde4euHXrYwYzufBXeMZ9p3Wku7VIwD\n" +
"4PfefBAZhzCJ+Dh937T/2dI/PqNIObZb28I7TXD/SQfwXurKDnGdl16LHmMcZ7bS\n" +
"d6AFgUd73b+Obh8=\n" +
"-----END PUBLIC KEY-----";
KeyFactory.getInstance("DSA").generatePublic(new X509EncodedKeySpec(PUBLIC_KEY_PEM.getBytes()));

但是我收到以下消息:

Exception in thread "main" java.security.spec.InvalidKeySpecException: Inappropriate key specification: invalid key format
at sun.security.provider.DSAKeyFactory.engineGeneratePublic(DSAKeyFactory.java:119)
at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
at com.dave.testing.RandomTesting.generatePublicKey2(RandomTesting.java:60)

为什么我的代码不正确?

最佳答案

您的 key 当前使用 base64 进行编码。为了使用 X509EncodedKeySpec 读取它,您需要对其进行解码。您可以使用任何 Base64 解码器来实现此目的,我目前使用的是 BouncyCaSTLe 提供的解码器。为此,您需要将其从非 Base64 部分中剥离(-----BEGIN PUBLIC KEY----------END PUBLIC KEY- ---- 分别为 行)。

以下代码片段使用org.bouncycaSTLe.util.encoders.Base64工作:

final String PUBLIC_KEY_PEM = "MIIBtzCCASsGByqGSM44BAEwggEeAoGBAJLJRIrDdiwbB6iWZTWowprJB8QfbLK7\n"
+ "8OUCoj6Ot5nfEL5VDPcc0v1rCGQxmL+nijPQsxA0LTucBySlkj6AvGIdND6yY7Qx\n"
+ "OZYeP6UErByzVhmDNG2MIhK7SL36O3uutOJKr86aTiDxP8/zSUO8JPZHqtr2K2Cm\n"
+ "lY6LQpocGnZ/AhUAmA/eq9AcGaNAqbT6ebB3IE3qWKkCgYAuh3zCz9aTPJ8+D9to\n"
+ "6xjjE6SEqKM4EDaA8kpV/363ad8kZRLRmtxTGDpIKV/k4ebb94+4o6VEFJKTUH7t\n"
+ "7c5uj8Hnr+8scctFE85nXprpK/CmxvWIZRl0AWjz1/8hoaUX3ZcLz9QbOLk1deSS\n"
+ "BksFgKZQgoaNVY3PPq0pjNfdCAOBhQACgYEAkDATEoqoCXMOy/LK+TOBqXWu3Tex\n"
+ "kkBMTJxYHyhXqmBLvvkiwBX1wz0i58Zg0Qde4euHXrYwYzufBXeMZ9p3Wku7VIwD\n"
+ "4PfefBAZhzCJ+Dh937T/2dI/PqNIObZb28I7TXD/SQfwXurKDnGdl16LHmMcZ7bS\n"
+ "d6AFgUd73b+Obh8=\n";
KeyFactory.getInstance("DSA").generatePublic(new X509EncodedKeySpec(Base64.decode(PUBLIC_KEY_PEM)));

关于java - 在 Java 中从 PEM 字符串创建 DSA 公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55162923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com