欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

golang ECIES加解密

程序员文章站 2024-03-14 10:44:22
...

这里使用golang来对消息进行加解密操作,ecies的**是通过ecdsa的**得到的,需要导包大佬的实现:“github.com/obscuren/ecies”,把包下下来,放到工作目录就可以,下面上代码了

package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"github.com/obscuren/ecies"
	"encoding/hex"
	"fmt"
	"crypto/x509"
)

func main() {
	var privateKey *ecdsa.PrivateKey

	//标准库生成ecdsa**对
	privateKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	//转为ecies**对
	var eciesPrivateKey *ecies.PrivateKey
	var eciesPublicKey *ecies.PublicKey
	eciesPrivateKey = ecies.ImportECDSA(privateKey)
	eciesPublicKey = &eciesPrivateKey.PublicKey

	var message string = "this is a message, 这是需要加密的数据"
	fmt.Println("原始数据: \n" + message)

	//加密
	cipherBytes, _ := ecies.Encrypt(rand.Reader, eciesPublicKey, []byte(message), nil, nil)
	//密文编码为16进制字符串输出
	cipherString := hex.EncodeToString(cipherBytes)

	fmt.Println("加密数据: \n" + cipherString)

	//解密
	//decrypeMessageBytes, _ := eciesPrivateKey.Decrypt(rand.Reader, cipherBytes, nil, nil)
	bytes, _ := hex.DecodeString(cipherString)
	decrypeMessageBytes, _ := eciesPrivateKey.Decrypt(rand.Reader, bytes, nil, nil)
	decrypeMessageString := string(decrypeMessageBytes[:])

	fmt.Println("解密数据: \n" + decrypeMessageString)
}
相关标签: golang 密码学