gpt4 book ai didi

java - 将字节数组转换回公钥

转载 作者:行者123 更新时间:2023-11-30 03:01:17 25 4
gpt4 key购买 nike

我有一个转换为字节数组的公钥。我想将其转换回公钥。我关注了这个link但出现错误:

Operation failed: javax.crypto.spec.SecretKeySpec incompatible with java.security.PublicKey

既然我知道它是公钥,有没有办法把它转换成 Publickey而不是SecretKey .

编辑

我使用RSAPublicKeySPec创建了一个公钥。现在没有错误,但是签名验证失败,因为当我看到新创建的公钥的 key Material 时,它与我通过的不一样。

我通过的关键 Material 3082010a0282010100ab7f161c0042496ccd6c6d4dadb919973435357776003acf54b7af1e440afb80b64a8755f8002cfeba6b184540a2d66086d74648346d75b8d71812b205387c0f6583bc4d7dc7ec114f3b176b7957c422e7d03fc6267fa2a6f89b9bee9e60a1d7c2d833e5a5f4bb0b1434f4e795a41100f8aa214900df8b65089f98135b1c67b701675abdbc7d5721aac9d14a7f081fcec80b64e8a0ecc8295353c795328abf70e1b42e7bb8b7f4e8ac8c810cdb66e3d21126eba8da7d0ca34142cb76f91f013da809e9c1b7ae64c54130fbc21d80e9c2cb06c5c8d7cce8946a9ac99b1c2815c3612a29a82d73a1f99374fe30e54951662a6eda29c6fc411335d5dc7426b0f6050203010001

使用 RSAPublicKeySpec 将其转换为公钥后获得的 key Material 30820122300D06092A864886F70D01010105000382010F003082010A0282010100AB7F161C0042496CCD6C6D4DADB919973435357776003ACF54B7AF1E440AFB80B64A8755F8002CFEBA6B184540A2D66086D74648346D75B8D71812B205387C0F6583BC4D7DC7EC114F3B176B7957C422E7D03FC6267FA2A6F89B9BEE9E60A1D7C2D833E5A5F4BB0B1434F4E795A41100F8AA214900DF8B65089F98135B1C67B701675ABDBC7D5721AAC9D14A7F081FCEC80B64E8A0ECC8295353C795328ABF70E1B42E7BB8B7F4E8AC8C810CDB66E3D21126EBA8DA7D0CA34142CB76F91F013DA809E9C1B7AE64C54130FBC21D80E9C2CB06C5C8D7CCE8946A9AC99B1C2815C3612A29A82D73A1F99374FE30E54951662A6EDA29C6FC411335D5DC7426B0F6050203010001

显然,由于 key Material 错误,验证将失败!我不明白为什么它会被改变。

但是当我直接使用 java.security.PublicKey 创建公钥时(匿名内部类),关键 Material 不会改变。但是当我通过它进行验证时,我收到错误的算法类型错误(我通过了RSA作为算法)

代码片段

    PublicKey pubKey = new PublicKey() {

private static final long serialVersionUID = 1L;

@Override
public String getFormat() {

return "PKCS1";
}

@Override
public byte[] getEncoded() {

return keyMat;
}

@Override
public String getAlgorithm() {

return "SHA256withRSA"; // tried with "RSA", getting same error
}
};

return pubKey;
}

最佳答案

检索自 Here

//Takes your byte array of the key as constructor parameter
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(myKeyBytes);

//Takes algorithm used to generate keys (DSA, RSA, DiffieHellman, etc.) as 1st parameter
//Takes security provider (SUN, BouncyCastle, etc.) as second parameter
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");

//Creates a new PublicKey object
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

关于java - 将字节数组转换回公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35867880/

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