From 9cbed73a22933afe8cecb7582043e2d10b40d060 Mon Sep 17 00:00:00 2001
From: dtapps
Date: Fri, 22 Dec 2023 11:48:17 +0800
Subject: [PATCH] update
---
goaes.go => aes.go | 0
go.mod | 2 +-
rsa.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++
version.go | 2 +-
4 files changed, 60 insertions(+), 2 deletions(-)
rename goaes.go => aes.go (100%)
create mode 100644 rsa.go
diff --git a/goaes.go b/aes.go
similarity index 100%
rename from goaes.go
rename to aes.go
diff --git a/go.mod b/go.mod
index b61ef4f..67542f3 100644
--- a/go.mod
+++ b/go.mod
@@ -1,3 +1,3 @@
module go.dtapp.net/goaes
-go 1.18
+go 1.21
diff --git a/rsa.go b/rsa.go
new file mode 100644
index 0000000..d8dd929
--- /dev/null
+++ b/rsa.go
@@ -0,0 +1,58 @@
+package goaes
+
+import (
+ "crypto"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/pem"
+ "errors"
+ "strings"
+)
+
+func RsaSign(signContent string, privateKey string, hash crypto.Hash) string {
+ shaNew := hash.New()
+ shaNew.Write([]byte(signContent))
+ hashed := shaNew.Sum(nil)
+ priKey, err := ParsePrivateKey(privateKey)
+ if err != nil {
+ panic(err)
+ }
+
+ signature, err := rsa.SignPKCS1v15(rand.Reader, priKey, hash, hashed)
+ if err != nil {
+ panic(err)
+ }
+ return base64.StdEncoding.EncodeToString(signature)
+}
+
+func ParsePrivateKey(privateKey string) (*rsa.PrivateKey, error) {
+ privateKey = FormatPrivateKey(privateKey)
+ // 2、解码私钥字节,生成加密对象
+ block, _ := pem.Decode([]byte(privateKey))
+ if block == nil {
+ return nil, errors.New("私钥信息错误")
+ }
+ // 3、解析DER编码的私钥,生成私钥对象
+ priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
+ if err != nil {
+ return nil, err
+ }
+ return priKey, nil
+}
+
+const (
+ PEM_BEGIN = "-----BEGIN RSA PRIVATE KEY-----\n"
+ PEM_END = "\n-----END RSA PRIVATE KEY-----"
+)
+
+func FormatPrivateKey(privateKey string) string {
+ if !strings.HasPrefix(privateKey, PEM_BEGIN) {
+ privateKey = PEM_BEGIN + privateKey
+ }
+ if !strings.HasSuffix(privateKey, PEM_END) {
+ privateKey = privateKey + PEM_END
+ }
+ return privateKey
+}
diff --git a/version.go b/version.go
index 4542fc0..e8b21cf 100644
--- a/version.go
+++ b/version.go
@@ -1,3 +1,3 @@
package goaes
-const Version = "1.0.0"
+const Version = "1.0.1"