Go 依存関係パッケージ
go get -u github.com/tjfoc/gmsm
SM2 楕円曲線公開鍵暗号化アルゴリズム
SM2 楕円曲線公開鍵暗号アルゴリズム 楕円曲線に基づく公開鍵暗号アルゴリズム SM2 は、
SM2 標準番号: GM/T 0003.1-2012、GM/T 0003.2-2012、GM/T 0003.3-2012、GM/T 0003.4-2012、 GM/T 0003.5-2012、GM/T 0009-2012、GM/T 0010-2012
依存パッケージ:github.com/tjfoc/gmsm/sm2
priv, err := sm2.GenerateKey(rand.Reader) // 生成密钥对
if err != nil {
log.Fatal(err)
}
msg := []byte("Tongji Fintech Research Institute")
pub := &priv.PublicKey
ciphertxt, err := pub.EncryptAsn1(msg,rand.Reader) //sm2加密
if err != nil {
log.Fatal(err)
}
fmt.Printf("加密结果:%x\n",ciphertxt)
plaintxt,err := priv.DecryptAsn1(ciphertxt) //sm2解密
if err != nil {
log.Fatal(err)
}
if !bytes.Equal(msg,plaintxt){
log.Fatal("原文不匹配")
}
sign,err := priv.Sign(rand.Reader, msg, nil) //sm2签名
if err != nil {
log.Fatal(err)
}
isok := pub.Verify(msg, sign) //sm2验签
fmt.Printf("Verified: %v\n", isok)
SM3 暗号化ハッシュ アルゴリズム
SM3 暗号化ハッシュ アルゴリズム - SM3
暗号化ハッシュ アルゴリズムが続く SM3 標準番号は次のとおりです。 GM/T 0004-2012
依存パッケージ:github.com/tjfoc/gmsm/sm3
data := "test"
h := sm3.New()
h.Write([]byte(data))
sum := h.Sum(nil)
fmt.Printf("digest value is: %x\n",sum)
SM4 ブロック暗号アルゴリズム
SM4 ブロック暗号アルゴリズム - SM4 ブロック暗号アルゴリズム
は、SM4 標準番号: GM/T 0002-2012
依存パッケージ:github.com/tjfoc/gmsm/sm4
import "crypto/cipher"
import "github.com/tjfoc/gmsm/sm4"
import "fmt"
func main(){
key := []byte("1234567890abcdef")
fmt.Printf("key = %v\n", key)
data := []byte{
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}
fmt.Printf("key = %v\n", key)
fmt.Printf("data = %x\n", data)
iv := []byte("0000000000000000")
err = SetIV(iv)//设置SM4算法实现的IV值,不设置则使用默认值
ecbMsg, err :=sm4.Sm4Ecb(key, data, true) //sm4Ecb模式pksc7填充加密
if err != nil {
t.Errorf("sm4 enc error:%s", err)
return
}
fmt.Printf("ecbMsg = %x\n", ecbMsg)
ecbDec, err := sm4.Sm4Ecb(key, ecbMsg, false) //sm4Ecb模式pksc7填充解密
if err != nil {
t.Errorf("sm4 dec error:%s", err)
return
}
fmt.Printf("ecbDec = %x\n", ecbDec)
}