~/snippets/go-pkcs7-decrypt
Published on

PKCS7 Decryption

472 words3 min read
package main

import (
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
	"log/slog"
	"os"

	"github.com/fullsailor/pkcs7"
)

func main() {
	enc := "<the encrypted string>"

	pk, err := os.ReadFile("priv.cert")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	pub, err := os.ReadFile("pub.cert")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	pemPK, _ := pem.Decode(pk)
	if pemPK == nil {
		fmt.Println("nil pemPK")
		os.Exit(1)
	}

	pubPK, _ := pem.Decode(pub)
	if pubPK == nil {
		fmt.Println("nil pubPK")
		os.Exit(1)
	}

	x509PK, err := x509.ParsePKCS1PrivateKey(pemPK.Bytes)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	x509PubCert, err := x509.ParseCertificate(pubPK.Bytes)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	p7b, err := base64.StdEncoding.DecodeString(enc)
	if err != nil {
		fmt.Println("base64 decode: ", err)
		os.Exit(1)
	}

	p7, err := pkcs7.Parse(p7b)
	if err != nil {
		fmt.Println("error parsing: ", err)
		os.Exit(1)
	}

	decOut, err := p7.Decrypt(x509PubCert, x509PK)
	if err != nil {
		slog.Error("Error decrypting output", "error", err)
		os.Exit(1)
	}

	fmt.Println(string(decOut))
}