// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved. //go:build script // +build script package js import ( "crypto/md5" "crypto/sha1" "crypto/sha256" "errors" "fmt" teaconst "github.com/TeaOSLab/EdgeNode/internal/const" ) func init() { if !teaconst.IsMain { return } SharedLibraryManager.Register(&JSCryptoLibrary{}) } type JSCryptoLibrary struct { JSBaseLibrary } func (this *JSCryptoLibrary) JSNamespace() string { return "gojs.JSCryptoLibrary" } func (this *JSCryptoLibrary) JSPrototype() string { return `gojs.md5 = function (s) { return $this.Md5(s) } gojs.sha1 = function (s) { return $this.Sha1(s) } gojs.sha256 = function (s) { return $this.Sha256(s) }` } func (this *JSCryptoLibrary) Md5(arguments *FunctionArguments) (string, error) { s, ok := arguments.StringAt(0) if !ok { return "", errors.New("invalid argument") } return fmt.Sprintf("%x", md5.Sum([]byte(s))), nil } func (this *JSCryptoLibrary) Sha1(arguments *FunctionArguments) (string, error) { s, ok := arguments.StringAt(0) if !ok { return "", errors.New("invalid argument") } return fmt.Sprintf("%x", sha1.Sum([]byte(s))), nil } func (this *JSCryptoLibrary) Sha256(arguments *FunctionArguments) (string, error) { s, ok := arguments.StringAt(0) if !ok { return "", errors.New("invalid argument") } return fmt.Sprintf("%x", sha256.Sum256([]byte(s))), nil }