从pem文件加载公私钥
package main
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
"os"
"io/ioutil"
"encoding/pem"
)
func main() {
var pri = os.Args[1]
var pub = os.Args[2]
var address = os.Args[3]
prik, _ := LoadPrivateKeyFile(pri)
pubk, _ := LoadPublicKeyFile(pub)
a, _ := RsaSignWithSha1Hex(address, prik)
fmt.Println(a)
err := RsaVerySignWithSha1Base64(address, a, pubk)
if err != nil {
fmt.Println(err)
}
}
//私钥签名
func RsaSignWithSha1Hex(data string, prvKey *rsa.PrivateKey) (string, error) {
h := sha256.New()
h.Write([]byte([]byte(data)))
hash := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, prvKey, crypto.SHA256, hash[:])
if err != nil {
fmt.Printf("Error from signing: %s\n", err)
return "", err
}
out := hex.EncodeToString(signature)
fmt.Println(signature)
return out, nil
}
func RsaVerySignWithSha1Base64(originalData, signData string, pubKey *rsa.PublicKey) error{
sign, err := hex.DecodeString(signData)
fmt.Println(sign)
if err != nil {
return err
}
hash := sha256.New()
hashed_int, err1 := hash.Write([]byte(originalData))
if err1 != nil {
fmt.Println(err1)
return err1
}
fmt.Println("hash int: ", hashed_int)
fmt.Println(hash.Sum(nil))
return rsa.VerifyPKCS1v15(pubKey, crypto.SHA256, hash.Sum(nil), sign)
}
// Load private key from private key file
func LoadPrivateKeyFile(keyfile string) (*rsa.PrivateKey, error) {
keybuffer, err := ioutil.ReadFile(keyfile)
if err != nil {
return nil, err
}
block, _ := pem.Decode([]byte(keybuffer))
if block == nil {
return nil, errors.New("private key error!")
}
privatekey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, errors.New("parse private key error!")
}
return privatekey, nil
}
func LoadPublicKeyFile(keyfile string) (*rsa.PublicKey, error) {
keybuffer, err := ioutil.ReadFile(keyfile)
if err != nil {
return nil, err
}
block, _ := pem.Decode(keybuffer)
if block == nil {
return nil, errors.New("public key error")
}
pubkeyinterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
publickey := pubkeyinterface.(*rsa.PublicKey)
return publickey, nil
}