XinYeYouKu/app/third/dfpOpenSdk/util/signature_test.go

66 lines
2.2 KiB
Go
Raw Normal View History

2024-07-08 18:01:02 +08:00
package util
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"github.com/emmansun/gmsm/sm2"
"log"
"math/big"
"testing"
)
func TestSignatureBySM2(t *testing.T) {
key, _ := sm2.GenerateKey(rand.Reader)
d := new(big.Int).SetBytes(key.D.Bytes()) // here we do NOT check if the d is in (0, N) or not
// Create private key from *big.Int
keyCopy := new(sm2.PrivateKey)
keyCopy.Curve = sm2.P256()
keyCopy.D = d
keyCopy.PublicKey.X, keyCopy.PublicKey.Y = keyCopy.ScalarBaseMult(keyCopy.D.Bytes())
fmt.Println(keyCopy)
if !key.Equal(keyCopy) {
log.Println("private key and copy should be equal")
}
pointBytes := elliptic.Marshal(key.Curve, key.X, key.Y)
// Create public key from point (uncompressed)
publicKeyCopy := new(ecdsa.PublicKey)
publicKeyCopy.Curve = sm2.P256()
publicKeyCopy.X, publicKeyCopy.Y = elliptic.Unmarshal(publicKeyCopy.Curve, pointBytes)
if !key.PublicKey.Equal(publicKeyCopy) {
log.Println("public key and copy should be equal")
}
}
func TestSM2_GenerateKeyPair(t *testing.T) {
pair, privateKey, _ := SM2_GenerateKeyPair()
log.Println(pair)
log.Println(privateKey)
}
2024-07-10 10:44:07 +08:00
func TestSM2_Sign(t *testing.T) {
// sm2 解密
privateKey := "ekUiEssevFHLcwNeRH0DqV6xJqasrVCPfdRzGmC2tJg="
encPassword := "BI9/V+ILZNtygiQ93L2bX0TxXjhsep7MZCvfJjXdLhPN7la4Cy/h3XveI5AMiaqSIRfplhfmnXTLLH9mlVX9AzLNI9vfrp6vzuHzFcM77h9bJK8YfTuqJGvjk+oqxyqDWXod0wPLWoxZx5EWDKDBf5CQkNI2hWiBJw=="
content, err := DecryptBySM2PrivateKey(privateKey, []byte(encPassword))
if err != nil {
log.Println(err)
} else {
log.Println("sm2解密=", string(content))
}
// sm4解密
encData := "fN6LHINSdu/QYzdWttl29yEVHrw2oFbxzBb/rLB64MVSDrHeXJbcA0fymmVKy2XHRCUQcFf2KlFYPLuVtBVN93xCGA+wRXuw/Xis926CoZ2ZzZMnBkLfmu7aEuRDdQtO32WICQBAU6MmrL2qolkhKCa4OOv8rHuco0btXBpF7BpLgR78RyCZKay90CLg27MfZOiEdIX4IcIwAnp/CLRH9xLJsosbFKZ5WnsBBu9e3DsxV0cjV1/VGR3vxfrUzX8msF85qpIktHUOY2b4UHDQDHUb1kiTH9RlGZ4sFDMfloMp/rOBjdNOqcelCcVn75bUAVuOlyjJPu1WIblpIPsmou7wW0TOjkuJPcfnVtAyvumSjknzpNSk1Rev0pT+qJyd853ME8Oy0+nrh3N5/wagFRTrpkIByc4b6JikqhGgj0fskXGiKXdkWfrBfM+By8zvWijSw71e5DZg1ZUFfgv9PQziiI7zl6vL/Qt1OrwkvIRt+8oftlWt3gLEeg+/qekC"
pwd := "9A9A4QyNz/pc8kZZXzhXOQ=="
result, err := SM4Decrypt2(encData, pwd)
if err != nil {
log.Println(err)
} else {
log.Println("sm4解密=", result)
}
}