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)
}
上一篇: 前端des加密,后端des解密
下一篇: Telnet 命令