add sm2、rsa

This commit is contained in:
Star 2024-11-09 00:13:49 +08:00
parent a405b83e69
commit 57314c7c02
4 changed files with 495 additions and 125 deletions

6
go.mod
View File

@ -4,18 +4,18 @@ go 1.18
require ( require (
apigo.cc/gojs v0.0.4 apigo.cc/gojs v0.0.4
github.com/ZZMarquis/gm v1.3.2
github.com/emmansun/gmsm v0.29.1
github.com/obscuren/ecies v0.0.0-20150213224233-7c0f4a9b18d9
github.com/ssgo/u v1.7.11 github.com/ssgo/u v1.7.11
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
) )
require ( require (
github.com/ZZMarquis/gm v1.3.2 // indirect
github.com/dlclark/regexp2 v1.11.4 // indirect github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/emmansun/gmsm v0.29.1 // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
github.com/obscuren/ecies v0.0.0-20150213224233-7c0f4a9b18d9 // indirect
github.com/ssgo/config v1.7.9 // indirect github.com/ssgo/config v1.7.9 // indirect
github.com/ssgo/log v1.7.7 // indirect github.com/ssgo/log v1.7.7 // indirect
github.com/ssgo/standard v1.7.7 // indirect github.com/ssgo/standard v1.7.7 // indirect

467
util.go
View File

@ -2,9 +2,13 @@ package util
import ( import (
"bytes" "bytes"
"crypto"
"crypto/ecdsa" "crypto/ecdsa"
"crypto/elliptic"
"crypto/hmac" "crypto/hmac"
"crypto/md5" "crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha1" "crypto/sha1"
"crypto/sha256" "crypto/sha256"
"crypto/sha512" "crypto/sha512"
@ -15,6 +19,7 @@ import (
"encoding/json" "encoding/json"
"encoding/pem" "encoding/pem"
"errors" "errors"
"math/big"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings" "strings"
@ -26,6 +31,8 @@ import (
"github.com/ZZMarquis/gm/sm3" "github.com/ZZMarquis/gm/sm3"
"github.com/ZZMarquis/gm/sm4" "github.com/ZZMarquis/gm/sm4"
"github.com/ZZMarquis/gm/util" "github.com/ZZMarquis/gm/util"
"github.com/emmansun/gmsm/sm2"
"github.com/emmansun/gmsm/smx509"
"github.com/obscuren/ecies" "github.com/obscuren/ecies"
"github.com/ssgo/u" "github.com/ssgo/u"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@ -191,37 +198,28 @@ func init() {
}, },
"genECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { "genECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm) args := gojs.MakeArgs(&argsIn, vm)
var pri, pub string var curve elliptic.Curve
var err error
switch args.Int(0) { switch args.Int(0) {
case 521: case 521:
pri, pub, err = u.GenECDSA521Key() curve = elliptic.P521()
case 384: case 384:
pri, pub, err = u.GenECDSA384Key() curve = elliptic.P384()
default: default:
pri, pub, err = u.GenECDSA256Key() curve = elliptic.P256()
}
if err == nil {
return vm.ToValue([]string{pri, pub})
} else {
panic(vm.NewGoError(err))
}
},
"exportECDSAPrivateKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
keyStr := args.Str(0)
var priKey *ecdsa.PrivateKey
var err error
if len(keyStr) >= 160 {
priKey, err = u.MakeECDSA521PrivateKey(keyStr)
} else if len(keyStr) >= 110 {
priKey, err = u.MakeECDSA384PrivateKey(keyStr)
} else {
priKey, err = u.MakeECDSA256PrivateKey(keyStr)
} }
pri, err := ecdsa.GenerateKey(curve, u.GlobalRand2)
if err != nil { if err != nil {
panic(vm.NewGoError(err)) panic(vm.NewGoError(err))
} }
var buf bytes.Buffer
buf.WriteByte(byte(len(pri.X.Bytes())))
buf.Write(pri.X.Bytes())
buf.Write(pri.Y.Bytes())
return vm.ToValue([][]byte{pri.D.Bytes(), buf.Bytes()})
},
"exportECDSAPrivateKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
priKey := makeECDSAPriKey(args.Bytes(0))
priBytes, err := x509.MarshalPKCS8PrivateKey(priKey) priBytes, err := x509.MarshalPKCS8PrivateKey(priKey)
if err != nil { if err != nil {
panic(vm.NewGoError(err)) panic(vm.NewGoError(err))
@ -234,19 +232,7 @@ func init() {
}, },
"exportECDSAPublicKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { "exportECDSAPublicKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1) args := gojs.MakeArgs(&argsIn, vm).Check(1)
keyStr := args.Str(0) pubKey := makeECDSAPubKey(args.Bytes(0))
var pubKey *ecdsa.PublicKey
var err error
if len(keyStr) >= 160 {
pubKey, err = u.MakeECDSA521PublicKey(keyStr)
} else if len(keyStr) >= 110 {
pubKey, err = u.MakeECDSA384PublicKey(keyStr)
} else {
pubKey, err = u.MakeECDSA256PublicKey(keyStr)
}
if err != nil {
panic(vm.NewGoError(err))
}
pubBytes, err := x509.MarshalPKIXPublicKey(pubKey) pubBytes, err := x509.MarshalPKIXPublicKey(pubKey)
if err != nil { if err != nil {
panic(vm.NewGoError(err)) panic(vm.NewGoError(err))
@ -290,8 +276,7 @@ func init() {
if ecdsaPriKey, ok := priKey.(*ecdsa.PrivateKey); !ok { if ecdsaPriKey, ok := priKey.(*ecdsa.PrivateKey); !ok {
panic(vm.NewGoError(errors.New("bad private key"))) panic(vm.NewGoError(errors.New("bad private key")))
} else { } else {
privateKey := base64.URLEncoding.EncodeToString(ecdsaPriKey.D.Bytes()) return vm.ToValue(ecdsaPriKey.D.Bytes())
return vm.ToValue(privateKey)
} }
} }
} else { } else {
@ -302,10 +287,10 @@ func init() {
panic(vm.NewGoError(errors.New("bad public key"))) panic(vm.NewGoError(errors.New("bad public key")))
} else { } else {
var buf bytes.Buffer var buf bytes.Buffer
buf.WriteByte(byte(len(ecdsaPubKey.X.Bytes())))
buf.Write(ecdsaPubKey.X.Bytes()) buf.Write(ecdsaPubKey.X.Bytes())
buf.Write(ecdsaPubKey.Y.Bytes()) buf.Write(ecdsaPubKey.Y.Bytes())
publicKey := base64.URLEncoding.EncodeToString(buf.Bytes()) return vm.ToValue(buf.Bytes())
return vm.ToValue(publicKey)
} }
} }
} }
@ -313,62 +298,33 @@ func init() {
"signECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { "signECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2) args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0) data := args.Bytes(0)
pri := args.Str(1) priKey := makeECDSAPriKey(args.Bytes(1))
var priKey *ecdsa.PrivateKey r, s, err := ecdsa.Sign(u.GlobalRand1, priKey, u.Sha256(data))
var err error
if len(pri) >= 80 {
priKey, err = u.MakeECDSA521PrivateKey(pri)
} else if len(pri) >= 55 {
priKey, err = u.MakeECDSA384PrivateKey(pri)
} else {
priKey, err = u.MakeECDSA256PrivateKey(pri)
}
if err != nil { if err != nil {
panic(vm.NewGoError(err)) panic(vm.NewGoError(err))
} }
if signature, err := u.SignECDSA(data, priKey); err == nil { var buf bytes.Buffer
return vm.ToValue(signature) buf.WriteByte(byte(len(r.Bytes())))
} else { buf.Write(r.Bytes())
panic(vm.NewGoError(err)) buf.Write(s.Bytes())
} return vm.ToValue(buf.Bytes())
}, },
"verifyECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { "verifyECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(3) args := gojs.MakeArgs(&argsIn, vm).Check(3)
data := args.Bytes(0) data := args.Bytes(0)
signature := args.Str(1) signature := args.Bytes(1)
pub := args.Str(2) pubKey := makeECDSAPubKey(args.Bytes(2))
var pubKey *ecdsa.PublicKey byteLen := signature[0]
var err error r := new(big.Int)
if len(pub) >= 160 { s := new(big.Int)
pubKey, err = u.MakeECDSA521PublicKey(pub) r.SetBytes(signature[1 : byteLen+1])
} else if len(pub) >= 110 { s.SetBytes(signature[byteLen+1:])
pubKey, err = u.MakeECDSA384PublicKey(pub) return vm.ToValue(ecdsa.Verify(pubKey, u.Sha256(data), r, s))
} else {
pubKey, err = u.MakeECDSA256PublicKey(pub)
}
if err != nil {
panic(vm.NewGoError(err))
}
return vm.ToValue(u.VerifyECDSA(data, signature, pubKey))
}, },
"encryptECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { "encryptECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(3) args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0) data := args.Bytes(0)
pub := args.Str(1) pubKey := makeECDSAPubKey(args.Bytes(1))
var pubKey *ecdsa.PublicKey
var err error
if len(pub) >= 80 {
pubKey, err = u.MakeECDSA521PublicKey(pub)
} else if len(pub) >= 60 {
pubKey, err = u.MakeECDSA384PublicKey(pub)
} else {
pubKey, err = u.MakeECDSA256PublicKey(pub)
}
if err != nil {
panic(vm.NewGoError(err))
}
eciesPubKey := ecies.ImportECDSAPublic(pubKey) eciesPubKey := ecies.ImportECDSAPublic(pubKey)
if r, err := ecies.Encrypt(u.GlobalRand1, eciesPubKey, data, nil, nil); err != nil { if r, err := ecies.Encrypt(u.GlobalRand1, eciesPubKey, data, nil, nil); err != nil {
panic(vm.NewGoError(err)) panic(vm.NewGoError(err))
@ -379,21 +335,7 @@ func init() {
"decryptECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { "decryptECDSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2) args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0) data := args.Bytes(0)
pri := args.Str(1) priKey := makeECDSAPriKey(args.Bytes(1))
var priKey *ecdsa.PrivateKey
var err error
if len(pri) >= 160 {
priKey, err = u.MakeECDSA521PrivateKey(pri)
} else if len(pri) >= 110 {
priKey, err = u.MakeECDSA384PrivateKey(pri)
} else {
priKey, err = u.MakeECDSA256PrivateKey(pri)
}
if err != nil {
panic(vm.NewGoError(err))
}
eciesPriKey := ecies.ImportECDSA(priKey) eciesPriKey := ecies.ImportECDSA(priKey)
if r, err := eciesPriKey.Decrypt(u.GlobalRand1, data, nil, nil); err != nil { if r, err := eciesPriKey.Decrypt(u.GlobalRand1, data, nil, nil); err != nil {
panic(vm.NewGoError(err)) panic(vm.NewGoError(err))
@ -401,7 +343,251 @@ func init() {
return vm.ToValue(r) return vm.ToValue(r)
} }
}, },
// TODO sm2 "genSM2": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
if pri, err := sm2.GenerateKey(u.GlobalRand2); err == nil {
var buf bytes.Buffer
buf.WriteByte(byte(len(pri.X.Bytes())))
buf.Write(pri.X.Bytes())
buf.Write(pri.Y.Bytes())
return vm.ToValue([][]byte{pri.D.Bytes(), buf.Bytes()})
} else {
panic(vm.NewGoError(err))
}
},
"exportSM2PrivateKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
priKey := makePriKey(args.Bytes(0), sm2.P256())
priBytes, err := smx509.MarshalECPrivateKey(priKey)
if err != nil {
panic(vm.NewGoError(err))
}
pemBytes := pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: priBytes,
})
return vm.ToValue(string(pemBytes))
},
"exportSM2PublicKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
pubKey := makePubKey(args.Bytes(0), sm2.P256())
pubBytes, err := smx509.MarshalPKIXPublicKey(pubKey)
if err != nil {
panic(vm.NewGoError(err))
}
pemBytes := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: pubBytes,
})
return vm.ToValue(string(pemBytes))
},
"importSM2Key": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
keyText := args.Str(0)
keyType := args.Str(1)
var keyBytes []byte
if strings.Contains(keyText, "-----BEGIN PRIVATE KEY-----") {
keyType = "private"
if block, _ := pem.Decode([]byte(keyText)); block == nil {
panic(vm.NewGoError(errors.New("bad private pem key")))
} else {
keyBytes = block.Bytes
}
} else if strings.Contains(keyText, "-----BEGIN PUBLIC KEY-----") {
keyType = "public"
if block, _ := pem.Decode([]byte(keyText)); block == nil {
panic(vm.NewGoError(errors.New("bad public pem key")))
} else {
keyBytes = block.Bytes
}
} else {
var err error
if keyBytes, err = base64.StdEncoding.DecodeString(keyText); err != nil {
panic(vm.NewGoError(err))
}
}
if keyType == "private" {
if priKey, err := smx509.ParseECPrivateKey(keyBytes); err != nil {
panic(vm.NewGoError(err))
} else {
return vm.ToValue(priKey.D.Bytes())
}
} else {
if pubKey, err := smx509.ParsePKIXPublicKey(keyBytes); err != nil {
panic(vm.NewGoError(err))
} else {
if sm2PubKey, ok := pubKey.(*ecdsa.PublicKey); !ok {
panic(vm.NewGoError(errors.New("bad public key")))
} else {
var buf bytes.Buffer
buf.WriteByte(byte(len(sm2PubKey.X.Bytes())))
buf.Write(sm2PubKey.X.Bytes())
buf.Write(sm2PubKey.Y.Bytes())
return vm.ToValue(buf.Bytes())
}
}
}
},
"signSM2": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0)
priKey := makePriKey(args.Bytes(1), sm2.P256())
if r, s, err := sm2.SignWithSM2(u.GlobalRand1, priKey, nil, data); err == nil {
var buf bytes.Buffer
buf.WriteByte(byte(len(r.Bytes())))
buf.Write(r.Bytes())
buf.Write(s.Bytes())
return vm.ToValue(buf.Bytes())
} else {
panic(vm.NewGoError(err))
}
},
"verifySM2": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(3)
data := args.Bytes(0)
signature := args.Bytes(1)
pubKey := makePubKey(args.Bytes(2), sm2.P256())
byteLen := signature[0]
r := new(big.Int)
s := new(big.Int)
r.SetBytes(signature[1 : byteLen+1])
s.SetBytes(signature[byteLen+1:])
return vm.ToValue(sm2.VerifyWithSM2(pubKey, nil, data, r, s))
},
"encryptSM2": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0)
pubKey := makePubKey(args.Bytes(1), sm2.P256())
if r, err := sm2.Encrypt(u.GlobalRand1, pubKey, data, nil); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"decryptSM2": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0)
priKey := makePriKey(args.Bytes(1), sm2.P256())
if r, err := sm2.Decrypt(&sm2.PrivateKey{PrivateKey: *priKey}, data); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"genRSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm)
size := args.Int(0)
if size == 0 {
size = 2048
}
key, err := rsa.GenerateKey(rand.Reader, size)
if err != nil {
panic(vm.NewGoError(err))
}
priBytes := x509.MarshalPKCS1PrivateKey(key)
pubBytes := x509.MarshalPKCS1PublicKey(&key.PublicKey)
return vm.ToValue([][]byte{priBytes, pubBytes})
},
"exportRSAPrivateKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
priKey := makeRSAPriKey(args.Bytes(0))
priBytes := x509.MarshalPKCS1PrivateKey(priKey)
pemBytes := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: priBytes,
})
return vm.ToValue(string(pemBytes))
},
"exportRSAPublicKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
pubKey := makeRSAPubKey(args.Bytes(0))
pubBytes := x509.MarshalPKCS1PublicKey(pubKey)
pemBytes := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: pubBytes,
})
return vm.ToValue(string(pemBytes))
},
"importRSAKey": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
keyText := args.Str(0)
keyType := args.Str(1)
var keyBytes []byte
if strings.Contains(keyText, "-----BEGIN RSA PRIVATE KEY-----") {
keyType = "private"
if block, _ := pem.Decode([]byte(keyText)); block == nil {
panic(vm.NewGoError(errors.New("bad private pem key")))
} else {
keyBytes = block.Bytes
}
} else if strings.Contains(keyText, "-----BEGIN RSA PUBLIC KEY-----") {
keyType = "public"
if block, _ := pem.Decode([]byte(keyText)); block == nil {
panic(vm.NewGoError(errors.New("bad public pem key")))
} else {
keyBytes = block.Bytes
}
} else {
var err error
if keyBytes, err = base64.StdEncoding.DecodeString(keyText); err != nil {
panic(vm.NewGoError(err))
}
}
if keyType == "private" {
if priKey, err := x509.ParsePKCS1PrivateKey(keyBytes); err != nil {
panic(vm.NewGoError(err))
} else {
return vm.ToValue(x509.MarshalPKCS1PrivateKey(priKey))
}
} else {
if pubKey, err := x509.ParsePKCS1PublicKey(keyBytes); err != nil {
panic(vm.NewGoError(err))
} else {
return vm.ToValue(x509.MarshalPKCS1PublicKey(pubKey))
}
}
},
"signRSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0)
priKey := makeRSAPriKey(args.Bytes(1))
signature, err := rsa.SignPKCS1v15(rand.Reader, priKey, crypto.SHA256, u.Sha256(data))
if err != nil {
panic(vm.NewGoError(err))
}
return vm.ToValue(signature)
},
"verifyRSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(3)
data := args.Bytes(0)
signature := args.Bytes(1)
pubKey := makeRSAPubKey(args.Bytes(2))
err := rsa.VerifyPKCS1v15(pubKey, crypto.SHA256, u.Sha256(data), signature)
return vm.ToValue(err == nil)
},
"encryptRSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0)
pubKey := makeRSAPubKey(args.Bytes(1))
encryptedData, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, data, nil)
if err != nil {
panic(vm.NewGoError(err))
}
return vm.ToValue(encryptedData)
},
"decryptRSA": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
data := args.Bytes(0)
priKey := makeRSAPriKey(args.Bytes(1))
decryptedData, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, priKey, data, nil)
if err != nil {
panic(vm.NewGoError(err))
}
return vm.ToValue(decryptedData)
},
"gzip": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { "gzip": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1) args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := u.Gzip(u.Bytes(args.Arguments[0].Export())); err == nil { if r, err := u.Gzip(u.Bytes(args.Arguments[0].Export())); err == nil {
@ -650,6 +836,26 @@ func init() {
args := gojs.MakeArgs(&argsIn, vm).Check(1) args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(filepath.IsLocal(args.Str(0))) return vm.ToValue(filepath.IsLocal(args.Str(0)))
}, },
"string": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.String(args.Any(0)))
},
"int": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.Int64(args.Any(0)))
},
"float": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.Float64(args.Any(0)))
},
"bytes": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.Bytes(args.Any(0)))
},
"bool": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.Bool(args.Any(0)))
},
} }
gojs.Register("apigo.cc/gojs/util", gojs.Module{ gojs.Register("apigo.cc/gojs/util", gojs.Module{
@ -658,3 +864,60 @@ func init() {
Example: utilMD, Example: utilMD,
}) })
} }
func makeECDSAPriKey(priKey []byte) *ecdsa.PrivateKey {
if len(priKey) >= 60 {
return makePriKey(priKey, elliptic.P521())
} else if len(priKey) >= 40 {
return makePriKey(priKey, elliptic.P384())
} else {
return makePriKey(priKey, elliptic.P256())
}
}
func makeECDSAPubKey(pubKey []byte) *ecdsa.PublicKey {
if len(pubKey) >= 130 {
return makePubKey(pubKey, elliptic.P521())
} else if len(pubKey) >= 90 {
return makePubKey(pubKey, elliptic.P384())
} else {
return makePubKey(pubKey, elliptic.P256())
}
}
func makePriKey(priKey []byte, curve elliptic.Curve) *ecdsa.PrivateKey {
x, y := curve.ScalarBaseMult(priKey)
return &ecdsa.PrivateKey{
D: new(big.Int).SetBytes(priKey),
PublicKey: ecdsa.PublicKey{
Curve: curve,
X: x,
Y: y,
},
}
}
func makePubKey(pubKey []byte, curve elliptic.Curve) *ecdsa.PublicKey {
keyLen := pubKey[0]
x := new(big.Int)
y := new(big.Int)
x.SetBytes(pubKey[1 : keyLen+1])
y.SetBytes(pubKey[keyLen+1:])
return &ecdsa.PublicKey{Curve: curve, X: x, Y: y}
}
func makeRSAPriKey(keyBytes []byte) *rsa.PrivateKey {
priKey, err := x509.ParsePKCS1PrivateKey(keyBytes)
if err != nil {
return nil
}
return priKey
}
func makeRSAPubKey(keyBytes []byte) *rsa.PublicKey {
pubKey, err := x509.ParsePKCS1PublicKey(keyBytes)
if err != nil {
return nil
}
return pubKey
}

83
util.ts
View File

@ -26,6 +26,22 @@ export default {
verifyECDSA, verifyECDSA,
encryptECDSA, encryptECDSA,
decryptECDSA, decryptECDSA,
genSM2,
exportSM2PrivateKey,
exportSM2PublicKey,
importSM2Key,
signSM2,
verifySM2,
encryptSM2,
decryptSM2,
genRSA,
exportRSAPrivateKey,
exportRSAPublicKey,
importRSAKey,
signRSA,
verifyRSA,
encryptRSA,
decryptRSA,
gzip, gzip,
gunzip, gunzip,
id, id,
@ -43,6 +59,7 @@ export default {
hmacSM3, hmacSM3,
tpl, tpl,
sleep, sleep,
setTimeout,
shell, shell,
toDatetime, toDatetime,
fromDatetime, fromDatetime,
@ -56,7 +73,12 @@ export default {
getPathVolume, getPathVolume,
absPath, absPath,
cleanPath, cleanPath,
isLocalPath isLocalPath,
string,
int,
float,
bytes,
bool,
} }
function json(data: any): string { return '' } function json(data: any): string { return '' }
@ -76,29 +98,45 @@ function aes(data: any, key: string, iv: string): string { return '' }
function unAes(data: string, key: string, iv: string): any { return null } function unAes(data: string, key: string, iv: string): any { return null }
function sm4(data: any, key: string, iv: string): string { return '' } function sm4(data: any, key: string, iv: string): string { return '' }
function unSM4(data: string, key: string, iv: string): any { return null } function unSM4(data: string, key: string, iv: string): any { return null }
function genECDSA(): string[] { return ['priKey', 'pubKey'] } function genECDSA(size?: number): any[] { return ['priKey', 'pubKey'] }
function exportECDSAPrivateKey(key: string): string { return '' } function exportECDSAPrivateKey(key: any): string { return '' }
function exportECDSAPublicKey(key: string): string { return '' } function exportECDSAPublicKey(key: any): string { return '' }
function importECDSAKey(pemKey: string): string { return '' } function importECDSAKey(pemKeyOrBase64: string, private_or_public_for_base64?: string): any { return '' }
function signECDSA(data: any, priKey: string): string { return '' } function signECDSA(data: any, priKey: any): any { return '' }
function verifyECDSA(data: any, signature: string, pubKey: string): string { return '' } function verifyECDSA(data: any, signature: any, pubKey: any): any { return '' }
function encryptECDSA(data: any, pubKey: string): string { return '' } function encryptECDSA(data: any, pubKey: any): any { return '' }
function decryptECDSA(data: any, priKey: string): string { return '' } function decryptECDSA(data: any, priKey: any): any { return '' }
function genSM2(): any[] { return ['priKey', 'pubKey'] }
function exportSM2PrivateKey(key: any): string { return '' }
function exportSM2PublicKey(key: any): string { return '' }
function importSM2Key(pemKeyOrBase64: string, private_or_public_for_base64?: string): any { return '' }
function signSM2(data: any, priKey: any): any { return '' }
function verifySM2(data: any, signature: any, pubKey: any): any { return '' }
function encryptSM2(data: any, pubKey: any): any { return '' }
function decryptSM2(data: any, priKey: any): any { return '' }
function genRSA(size?: number): any[] { return ['priKey', 'pubKey'] }
function exportRSAPrivateKey(key: any): string { return '' }
function exportRSAPublicKey(key: any): string { return '' }
function importRSAKey(pemKeyOrBase64: string, private_or_public_for_base64?: string): any { return '' }
function signRSA(data: any, priKey: any): any { return '' }
function verifyRSA(data: any, signature: any, pubKey: any): any { return '' }
function encryptRSA(data: any, pubKey: any): any { return '' }
function decryptRSA(data: any, priKey: any): any { return '' }
function gzip(data: any): string { return '' } function gzip(data: any): string { return '' }
function gunzip(data: string): any { return null } function gunzip(data: string): any { return null }
function id(): string { return '' } function id(): string { return '' }
function uniqueId(): string { return '' } function uniqueId(): string { return '' }
function token(size: number): string { return '' } function token(size: number): any { return '' }
function md5(...data: any[]): string { return '' } function md5(...data: any[]): any { return '' }
function sha1(...data: any[]): string { return '' } function sha1(...data: any[]): any { return '' }
function sha256(...data: any[]): string { return '' } function sha256(...data: any[]): any { return '' }
function sha512(...data: any[]): string { return '' } function sha512(...data: any[]): any { return '' }
function sm3(...data: any[]): string { return '' } function sm3(...data: any[]): any { return '' }
function hmacMD5(key: any, ...data: any[]): string { return '' } function hmacMD5(key: any, ...data: any[]): any { return '' }
function hmacSHA1(key: any, ...data: any[]): string { return '' } function hmacSHA1(key: any, ...data: any[]): any { return '' }
function hmacSHA256(key: any, ...data: any[]): string { return '' } function hmacSHA256(key: any, ...data: any[]): any { return '' }
function hmacSHA512(key: any, ...data: any[]): string { return '' } function hmacSHA512(key: any, ...data: any[]): any { return '' }
function hmacSM3(key: any, ...data: any[]): string { return '' } function hmacSM3(key: any, ...data: any[]): any { return '' }
function tpl(text: string, data: any, functions?: Object): string { return '' } function tpl(text: string, data: any, functions?: Object): string { return '' }
function sleep(ms: number): void { } function sleep(ms: number): void { }
function setTimeout(callback: () => void, ms?: number, ...args: any): void { } function setTimeout(callback: () => void, ms?: number, ...args: any): void { }
@ -116,3 +154,8 @@ function getPathVolume(path: string): string { return '' }
function absPath(path: string): string { return '' } function absPath(path: string): string { return '' }
function cleanPath(path: string): string { return '' } function cleanPath(path: string): string { return '' }
function isLocalPath(path: string): boolean { return false } function isLocalPath(path: string): boolean { return false }
function string(value: any): string { return '' }
function int(value: any): number { return 0 }
function float(value: any): number { return 0 }
function bytes(value: any): any { return null }
function bool(value: any): boolean { return false }

View File

@ -44,11 +44,75 @@ func TestECDSA(t *testing.T) {
r, err := gojs.Run(` r, err := gojs.Run(`
import util from 'apigo.cc/gojs/util' import util from 'apigo.cc/gojs/util'
let [pri, pub] = util.genECDSA() let [pri, pub] = util.genECDSA()
let priPem = util.exportECDSAPrivateKey(pri)
let pubPem = util.exportECDSAPublicKey(pub)
pri = util.importECDSAKey(priPem)
pub = util.importECDSAKey(pubPem)
let text = 'hello 123' let text = 'hello 123'
let sign = util.signECDSA(text, pri) let sign = util.signECDSA(text, pri)
let verify = util.verifyECDSA(text, sign, pub) let verify = util.verifyECDSA(text, sign, pub)
if(!verify) return 'failed to verify sign '+sign if(!verify) return 'failed to verify sign '+sign
let textEnc = util.encryptECDSA(text, pub)
let textDec = util.decryptECDSA(textEnc, pri)
if(util.string(textDec)!==text) return 'failed to encrypt by ECDSA '+util.hex(textEnc)
return true
`, "")
if err != nil {
t.Fatal(err)
}
if r != true {
t.Fatal(r)
}
fmt.Println(u.Green("ecdsa test passed"))
}
func TestSM2(t *testing.T) {
r, err := gojs.Run(`
import util from 'apigo.cc/gojs/util'
let [pri, pub] = util.genSM2()
let priPem = util.exportSM2PrivateKey(pri)
let pubPem = util.exportSM2PublicKey(pub)
pri = util.importSM2Key(priPem)
pub = util.importSM2Key(pubPem)
let text = 'hello 123'
let sign = util.signSM2(text, pri)
let verify = util.verifySM2(text, sign, pub)
if(!verify) return 'failed to verify sign '+sign
let textEnc = util.encryptSM2(text, pub)
let textDec = util.decryptSM2(textEnc, pri)
if(util.string(textDec)!==text) return 'failed to encrypt by SM2 '+util.hex(textEnc)
return true
`, "")
if err != nil {
t.Fatal(err)
}
if r != true {
t.Fatal(r)
}
fmt.Println(u.Green("ecdsa test passed"))
}
func TestRSA(t *testing.T) {
r, err := gojs.Run(`
import util from 'apigo.cc/gojs/util'
let [pri, pub] = util.genRSA()
let priPem = util.exportRSAPrivateKey(pri)
let pubPem = util.exportRSAPublicKey(pub)
pri = util.importRSAKey(priPem)
pub = util.importRSAKey(pubPem)
let text = 'hello 123'
let sign = util.signRSA(text, pri)
let verify = util.verifyRSA(text, sign, pub)
if(!verify) return 'failed to verify sign '+sign
let textEnc = util.encryptRSA(text, pub)
let textDec = util.decryptRSA(textEnc, pri)
if(util.string(textDec)!==text) return 'failed to encrypt by RSA '+util.hex(textEnc)
return true return true
`, "") `, "")
if err != nil { if err != nil {