liboqs-go库在Mac编译使用

liboqs-go库在Mac编译使用

liboqs-go是liboqs——量子安全密码算法的开源C库的go封装

将在mac m1上部署和开发使用,所以简单记录下过程

部署

# 安装基础依赖工具
brew install cmake ninja [email protected] wget doxygen graphviz astyle valgrind
pip3 install pytest pytest-xdist pyyaml

# 下载c库
git clone -b main https://github.com/open-quantum-safe/liboqs.git
cd liboqs

# 编译c库 启用共享库
mkdir build && cd build
cmake -DBUILD_SHARED_LIBS=ON -GNinja ..
ninja

# 设置指向 liboqs 库目录的路径
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

# 下载go的封装库
cd /opt && git clone https://github.com/open-quantum-safe/liboqs-go

# 添加到环境变量
export LIBOQSGO_INSTALL_PATH=/opt/liboqs-go

# 配置加到环境变量
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/opt/liboqs-go/.config

# 测试
cd /opt/liboqs-go
go run examples/kem/kem.go

# 在项目中使用
go get github.com/open-quantum-safe/liboqs-go/oqs

简单实用案例-生成私钥、公钥、证书并存文件

package main

import (
	"encoding/pem"
	"fmt"
	"log"
	"os"

	"github.com/open-quantum-safe/liboqs-go/oqs"
)

func main() {
	//fmt.Println("liboqs version: " + oqs.LiboqsVersion())
	//fmt.Println("Enabled signatures:")
	//fmt.Println(oqs.EnabledSigs())

	sigName := "Dilithium2"
	signer := oqs.Signature{}
	defer signer.Clean() // clean up even in case of panic

	if err := signer.Init(sigName, nil); err != nil {
		log.Fatal(err)
	}

	//fmt.Println("\nSignature details:")
	//fmt.Println(signer.Details())

	msg := []byte("This is the message to sign")
	pubKey, err := signer.GenerateKeyPair()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("\nSigner public key:\n% X ... % X\n", pubKey[0:8],
		pubKey[len(pubKey)-8:])

	signature, _ := signer.Sign(msg)
	fmt.Printf("\nSignature:\n% X ... % X\n", signature[0:8],
		signature[len(signature)-8:])

	verifier := oqs.Signature{}
	defer verifier.Clean() // clean up even in case of panic

	if err := verifier.Init(sigName, nil); err != nil {
		log.Fatal(err)
	}

	isValid, err := verifier.Verify(msg, signature, pubKey)
	if err != nil {
		log.Fatal(err)
	}

	verifier.ExportSecretKey()

	fmt.Println("\nValid signature?", isValid)

	// 私钥 存文件
	prvKeyFile, err := os.Create("prvKey.pem")
	defer prvKeyFile.Close()
	if err != nil {
		return
	}
	err = pem.Encode(prvKeyFile, &pem.Block{Type: "PRIVATE", Bytes: signer.ExportSecretKey()})
	if err != nil {
		return
	}

	// 公钥 存文件
	pubKeyFile, err := os.Create("pubKey.pem")
	defer pubKeyFile.Close()
	if err != nil {
		return
	}
	err = pem.Encode(pubKeyFile, &pem.Block{Type: "PUBLIC", Bytes: pubKey})
	if err != nil {
		return
	}

	// 证书 存文件
	certFile, err := os.Create("cert.pem")
	defer certFile.Close()
	if err != nil {
		return
	}
	cert, _ := signer.Sign(pubKey)
	err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: cert})
	if err != nil {
		return
	}

}

参考

  • 编译 https://github.com/open-quantum-safe/liboqs#linuxmacos
  • 环境变量及使用 https://github.com/open-quantum-safe/liboqs-go

你可能感兴趣的:(#,3.6.,go,golang,macos,开发语言)