You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OpenSSL生成PKCS#7后,用go.mozilla.org/pkcs7解析报'tags don't match'错误

问题:生成的PKCS#7文件是否有效?

我用以下OpenSSL命令生成测试用PKCS#7文件cert.p7b:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=US/ST=CA/L=San Francisco/O=Acme Corporation/OU=Awesomeness Department/CN=Insanely Great Certificate"
openssl crl2pkcs7 -nocrl -certfile cert.pem -out cert.p7b

但用pkcs7 Go包解析时:

package main

import (
    "os"

    "go.mozilla.org/pkcs7"
)

func main() {
    b, err := os.ReadFile("cert.p7b")
    if err != nil {
        panic(err)
    }

    if _, err := pkcs7.Parse(b); err != nil {
        panic(err)
    }
}

出现标签不匹配错误:

> go run main.go
panic: asn1: structure error: tags don't match (16 vs {class:0 tag:13 length:77 isCompound:true}) {optional:false explicit:false application:false private:false defaultValue:<nil> tag:<nil> stringType:0 timeType:0 set:false omitEmpty:false} contentInfo @2

请问该PKCS#7文件是否为有效文件?


解答

你的cert.p7b是有效的PKCS#7文件,解析报错仅因格式不匹配:

  • OpenSSL的crl2pkcs7命令默认输出PEM格式的PKCS#7文件(文件开头带有-----BEGIN PKCS7-----标记)
  • go.mozilla.org/pkcs7包的Parse方法默认仅支持DER格式的二进制数据,无法直接解析PEM格式的文本内容

验证文件有效性

可以用OpenSSL命令直接验证文件有效性:

openssl pkcs7 -in cert.p7b -noout -text

如果能正常输出证书详细信息,说明文件本身是标准有效的PKCS#7结构。

解决解析报错的方法

有两种方式让Go代码正常解析:

  1. 转换文件为DER格式
    用OpenSSL将PEM格式转换为DER格式:

    openssl pkcs7 -in cert.p7b -out cert.p7d -outform DER
    

    之后修改Go代码读取cert.p7d即可。

  2. 在Go代码中处理PEM解码
    在调用pkcs7.Parse前,先对PEM格式内容进行解码:

    package main
    
    import (
        "encoding/pem"
        "os"
    
        "go.mozilla.org/pkcs7"
    )
    
    func main() {
        b, err := os.ReadFile("cert.p7b")
        if err != nil {
            panic(err)
        }
    
        // 解码PEM格式内容
        block, _ := pem.Decode(b)
        if block == nil || block.Type != "PKCS7" {
            panic("failed to decode PEM PKCS7 block")
        }
    
        if _, err := pkcs7.Parse(block.Bytes); err != nil {
            panic(err)
        }
    }
    

内容的提问来源于stack exchange,提问作者Kurt Peek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 20:35:08