package util_test import ( "bytes" "crypto/hmac" "crypto/sha256" "fmt" "testing" "time" "apigo.cc/gojs" _ "apigo.cc/gojs/util" "github.com/ZZMarquis/gm/sm3" "github.com/ssgo/u" ) func TestHash(t *testing.T) { vm := gojs.New() vm.RunCode("import util from 'apigo.cc/gojs/util'") testIsSame(vm, t, "util.md5('hello 123')", u.MD5([]byte("hello 123"))) testIsSame(vm, t, "util.base64(util.md5('hello 123'))", u.MD5Base64("hello 123")) testIsSame(vm, t, "util.hex(util.md5('hello 123'))", u.MD5String("hello 123")) testIsSame(vm, t, "util.sha1('hello',' 123')", u.Sha1([]byte("hello 123"))) testIsSame(vm, t, "util.sha256('hello 123')", u.Sha256([]byte("hello 123"))) testIsSame(vm, t, "util.sha512('hello 123')", u.Sha512([]byte("hello 123"))) sm3Hash := sm3.New() sm3Hash.Write([]byte("hello 123")) testIsSame(vm, t, "util.sm3('hello 123')", sm3Hash.Sum(nil)) hash := hmac.New(sha256.New, []byte("abc")) hash.Write([]byte("hello 123")) // hmacTestValue := u.HmacSha1([]byte("hello 123"), testIsSame(vm, t, "util.hmacSHA256('abc', 'hello 123')", hash.Sum(nil)) testIsSame(vm, t, "util.json('hello 123')", u.Json("hello 123")) testIsSame(vm, t, "util.yaml('hello 123')", u.Yaml("hello 123")) testIsSame(vm, t, "util.aes('hello 123','12345678901234567','12345678901234567')", u.EncryptAes("hello 123", []byte("12345678901234567"), []byte("12345678901234567"))) sm4R, _ := vm.RunCode("util.hex(util.sm4('hello 123','12345678901234567','12345678901234567'))") testIsSame(vm, t, "util.unSM4('"+u.String(sm4R)+"','12345678901234567','12345678901234567')", "hello 123") testIsSame(vm, t, "util.gzip('hello 123')", u.GzipN([]byte("hello 123"))) tm, _ := time.ParseInLocation("2006-01-02 15:04:05", "2024-01-01 00:00:00", time.Local) testIsSame(vm, t, "util.fromDatetime('2024-01-01 00:00:00')", tm.UnixMilli()) } func TestECDSA(t *testing.T) { r, err := gojs.Run(` import util from 'apigo.cc/gojs/util' let [pri, pub] = util.genECDSA() let text = 'hello 123' let sign = util.signECDSA(text, pri) let verify = util.verifyECDSA(text, sign, pub) if(!verify) return 'failed to verify sign '+sign return true `, "") if err != nil { t.Fatal(err) } if r != true { t.Fatal(r) } fmt.Println(u.Green("ecdsa test passed")) } func testIsSame(vm *gojs.Runtime, t *testing.T, code string, checkValue any) { r, err := vm.RunCode(code) if err != nil { t.Fatal(code, err) return } if data, ok := r.([]byte); ok { if !bytes.Equal(data, u.Bytes(r)) { t.Fatal(code, r) return } } else { if r != checkValue { t.Fatal(code, r, checkValue) return } } fmt.Println(u.Green(code)) }