gpt4 book ai didi

java - Android、Java 上 PEM 文件中的公钥

转载 作者:行者123 更新时间:2023-11-30 00:25:27 24 4
gpt4 key购买 nike

基本上我正在尝试验证使用 openssl 的签名,如下所示:

openssl dgst -sha256 -verify prime192v1-pub-v1.pem -signature signatureFile.bin < dataFile.bin

... 为了在 android 上执行此操作,我需要创建 PublicKey 对象。我正在使用的方法在 kf.generatePublic(new X509EncodedKeySpec(encoded)) 行抛出 java.security.spec.InvalidKeySpecException: Unexpected key type

import org.spongycastle.util.encoders.Base64;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

public class SO {

public static PublicKey getPublicKeyFromString(String key) throws IOException, GeneralSecurityException {
String publicKeyPEM = key;
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.decode(publicKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(new X509EncodedKeySpec(encoded));
}

}

这是我调用方法的方式:

    SO.getPublicKeyFromString(
"-----BEGIN PUBLIC KEY-----\n" +
"MEkwEwYHKoZIzj0CAQYIKoZIzj0DAQEDMgAEXMHnQfWiM4oCaLfx296llgz7iaVv\n" +
"avMPppkzVNZAxtlNLhFlXnNWD0Mw9yzP8/Go\n" +
"-----END PUBLIC KEY-----"
);

有人知道我做错了什么吗?

最佳答案

我成功了。公钥是椭圆曲线(p192)公钥,应该不同地加载。有了 PublicKey,我就能够像使用 openssl 命令一样验证签名。

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.Reader;
import java.io.StringReader;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

public class SO {

public PublicKey getPublicKey() throws Exception {
Security.addProvider(new BouncyCastleProvider());
Reader rdr = new StringReader(
"-----BEGIN PUBLIC KEY-----\n" +
"MEkwEwYHKoZIzj0CAQYIKoZIzj0DAQEDMgAEXMHnQfWiM4oCaLfx296llgz7iaVv\n" +
"avMPppkzVNZAxtlNLhFlXnNWD0Mw9yzP8/Go\n" +
"-----END PUBLIC KEY-----\n"
); // or from file etc.

org.bouncycastle.util.io.pem.PemObject spki = new org.bouncycastle.util.io.pem.PemReader(rdr).readPemObject();
PublicKey key = KeyFactory.getInstance("EC", "BC").generatePublic(new X509EncodedKeySpec(spki.getContent()));
return key;
}

public static boolean verify(byte[] data, byte[] signatureBytes, PublicKey publicKey) throws Exception {
Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
signature.initVerify(publicKey);
signature.update(data);
return signature.verify(signatureBytes);
}

}

关于java - Android、Java 上 PEM 文件中的公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45464949/

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