加密解密
在Go语言中提供了几种数据的加密和解密的方法。
md5
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func main() {
msg := "Hello Go!"
h := md5.New() // 创建一个md5 hash对象
h.Write([]byte(msg)) // 写入加密的内容
sum := h.Sum(nil) // 加密
md := hex.EncodeToString(sum) // 转成16进制
fmt.Println(md)
}
md5 是一种不可逆的加密方式。
SHA256
func main() {
msg := "Hello GO!"
h := sha256.New()
h.Write([]byte(msg))
shaMsg := hex.EncodeToString(h.Sum(nil))
fmt.Println(shaMsg)
}
RSA
这是一种非对称加密算法,一般通过公钥加密,私钥解密。
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"log"
)
// 生成密钥对
func GenerateKey(bit int) (privateKey, publicKey []byte, err error) {
private, err := rsa.GenerateKey(rand.Reader, bit)
derSteam := x509.MarshalPKCS1PrivateKey(private)
blockPrivateKey := &pem.Block{
Type: "RSA SSH PRIVATE KEY",
Bytes: derSteam,
}
privateKey = pem.EncodeToMemory(blockPrivateKey)
public := &private.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(public)
blockPublicKey := &pem.Block{
Type: "RSA SSH PUBLIC KEY",
Bytes: derPkix,
}
publicKey = pem.EncodeToMemory(blockPublicKey)
return
}
// 加密
func RsaEncrypt(publicKey, data []byte) ([]byte, error) {
block, _ := pem.Decode(publicKey)
if block == nil {
return nil, errors.New("public key error")
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
pub := pubInterface.(*rsa.PublicKey)
return rsa.EncryptPKCS1v15(rand.Reader, pub, data)
}
// 解密
func RsaDecrypt(privateKey, data []byte) ([]byte, error) {
block, _ := pem.Decode(privateKey)
if block == nil {
return nil, errors.New("private key error")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return rsa.DecryptPKCS1v15(rand.Reader, priv, data)
}
func main() {
msg := "Hello GO!"
privateKey, publicKey, err := GenerateKey(1024)
if err != nil {
log.Fatal(err.Error())
}
EncodeMsg, err := RsaEncrypt(publicKey, []byte(msg))
if err != nil {
log.Fatal(err.Error())
}
DecodeMsg, err := RsaDecrypt(privateKey, EncodeMsg)
if err != nil {
log.Fatal(err.Error())
}
fmt.Printf("原来数据:%s\n", msg)
fmt.Printf("加密数据: %s\n", string(EncodeMsg))
fmt.Printf("解密数据:%s\n", string(DecodeMsg))
}
Last updated
Was this helpful?