以下是Java代码示例,可以实现对pem格式的公钥解析并验签:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class VerifySignature {

    public static void main(String[] args) throws Exception {
        // 读取pem格式的公钥文件
        String publicKeyFilePath = "/path/to/public_key.pem";
        String publicKeyString = readFromFile(publicKeyFilePath);

        // 解析公钥
        PublicKey publicKey = getPublicKeyFromPem(publicKeyString);

        // 待验签的数据
        String data = "hello world";

        // 签名
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initVerify(publicKey);
        signature.update(data.getBytes());
        String signatureString = "signature in base64"; // 待验签的签名,以base64编码的字符串
        byte[] signatureBytes = Base64.getDecoder().decode(signatureString.getBytes());

        // 验签
        boolean result = signature.verify(signatureBytes);
        System.out.println("验签结果:" + result);
    }

    /**
     * 从pem格式的字符串中获取公钥对象
     */
    private static PublicKey getPublicKeyFromPem(String publicKeyString) throws Exception {
        // 去掉pem格式的头尾信息
        publicKeyString = publicKeyString.replaceAll("-----BEGIN PUBLIC KEY-----", "");
        publicKeyString = publicKeyString.replaceAll("-----END PUBLIC KEY-----", "");

        // base64解码
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString.getBytes());

        // 生成公钥对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 从文件中读取字符串
     */
    private static String readFromFile(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        return sb.toString();
    }
}

解析公钥的方法 getPublicKeyFromPem 中,我们首先去掉pem格式的头尾信息,然后对公钥进行base64解码,最后生成公钥对象。在验签时,我们使用公钥对象初始化 Signature 对象,并调用 verify 方法进行验签,最终得到验签结果


原文地址: https://www.cveoy.top/t/topic/g1d8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录