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))
}